演练:在后台运行操作
来源:互联网 发布:java核心技术 mobi 编辑:程序博客网 时间:2024/05/07 01:10
http://msdn.microsoft.com/zh-cn/library/vstudio/ms233672(v=vs.100).aspx
如果有一个需要很长时间才能完成的操作,而且不希望用户界面中出现延迟,则可以使用 BackgroundWorker 类来在另一个线程上运行该操作。
有关此示例中所用代码的完整清单,请参见 如何:在后台运行操作。
显示的对话框和菜单命令可能会与“帮助”中的描述不同,具体取决于您现用的设置或版本。 若要更改设置,请在“工具”菜单上选择“导入和导出设置”。 有关更多信息,请参见 使用设置。
在后台运行操作
当窗体在 Windows 窗体设计器中处于活动状态时,将两个 Button 控件从“工具箱”拖动到窗体中,然后根据下表设置这两个按钮的 Name 和 Text 属性。
按钮
名称
文本
button1
startBtn
启动
button2
cancelBtn
取消
打开“工具箱”,单击“组件”选项卡,然后将 BackgroundWorker 组件拖动到窗体上。
backgroundWorker1 组件显示在“组件栏”中。
在“属性”窗口中,将 WorkerSupportsCancellation 属性设置为 true。
在“属性”窗口中,单击“事件”按钮,然后双击 DoWork 和 RunWorkerCompleted 事件以创建事件处理程序。
将耗时的代码插入到 DoWork 事件处理程序中。
从 DoWorkEventArgs 参数的 Argument 属性中提取该操作所需的所有参数。
将计算的结果赋给 DoWorkEventArgs 的 Result 属性。
计算结果可供 RunWorkerCompleted 事件处理程序使用。
C#VBprivate void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){ // Do not access the form's BackgroundWorker reference directly. // Instead, use the reference provided by the sender parameter. BackgroundWorker bw = sender as BackgroundWorker; // Extract the argument. int arg = (int)e.Argument; // Start the time-consuming operation. e.Result = TimeConsumingOperation(bw, arg); // If the operation was canceled by the user, // set the DoWorkEventArgs.Cancel property to true. if (bw.CancellationPending) { e.Cancel = true; }}
在 RunWorkerCompleted 事件处理程序中,插入用来检索操作结果的代码。
C#VB// This event handler demonstrates how to interpret // the outcome of the asynchronous operation implemented// in the DoWork event handler.private void backgroundWorker1_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e){ if (e.Cancelled) { // The user canceled the operation. MessageBox.Show("Operation was canceled"); } else if (e.Error != null) { // There was an error during the operation. string msg = String.Format("An error occurred: {0}", e.Error.Message); MessageBox.Show(msg); } else { // The operation completed normally. string msg = String.Format("Result = {0}", e.Result); MessageBox.Show(msg); }}
实现 TimeConsumingOperation 方法。
C#VB// This method models an operation that may take a long time // to run. It can be cancelled, it can raise an exception,// or it can exit normally and return a result. These outcomes// are chosen randomly.private int TimeConsumingOperation( BackgroundWorker bw, int sleepPeriod ){ int result = 0; Random rand = new Random(); while (!bw.CancellationPending) { bool exit = false; switch (rand.Next(3)) { // Raise an exception. case 0: { throw new Exception("An error condition occurred."); break; } // Sleep for the number of milliseconds // specified by the sleepPeriod parameter. case 1: { Thread.Sleep(sleepPeriod); break; } // Exit and return normally. case 2: { result = 23; exit = true; break; } default: { break; } } if( exit ) { break; } } return result;}
在 Windows 窗体设计器中双击 startButton,创建新的 Click 事件处理程序。
在 startButton 的 Click 事件处理程序中,调用 RunWorkerAsync 方法。
C#VBprivate void startBtn_Click(object sender, EventArgs e){ this.backgroundWorker1.RunWorkerAsync(2000);}
在 Windows 窗体设计器中双击 cancelButton,创建新的 Click 事件处理程序。
在 cancelButton 的 Click 事件处理程序中,调用 CancelAsync 方法。
C#VBprivate void cancelBtn_Click(object sender, EventArgs e){ this.backgroundWorker1.CancelAsync();}
在文件的顶部,导入 System.ComponentModel 和 System.Threading 命名空间。
C#VBusing System;using System.ComponentModel;using System.Drawing;using System.Threading;using System.Windows.Forms;
按 F6 生成解决方案,然后按 Ctrl-F5 在调试器外部运行该应用程序。
如果按 F5 在调试器中运行应用程序,则调试器将捕捉和显示在 TimeConsumingOperation 方法中引发的异常。 当在调试器外部运行应用程序时,BackgroundWorker 将处理该异常并将其缓存在RunWorkerCompletedEventArgs 的 Error 属性中。
单击“启动”按钮运行异步操作,然后单击“取消”按钮停止正在运行的异步操作。
每个操作的结果均在 MessageBox 中显示。
实现一个该窗体,该窗体随着异步操作的进行报告进度。有关更多信息,请参见 如何:实现使用后台操作的窗体。
实现支持组件异步模式的类。有关更多信息,请参见 实现基于事件的异步模式。
任务
参考
其他资源
- 演练:在后台运行操作
- 如何:在后台运行操作
- voip在后台运行
- NSTimer在后台运行
- 在后台运行软件
- 在后台运行rtorrent
- python在后台运行
- C#在后台运行操作:BackgroundWorker的用法
- C#在后台运行操作:BackgroundWorker的用法
- 将程序运行在后台
- linux在后台运行程序
- ios 程序在后台运行
- 隐藏bat在后台运行
- 判断应用在后台运行
- 维持程序在后台运行
- Linux 在后台运行程序
- 设置App运行在后台
- iOS在后台运行app
- Java:变量的赋值操作(祭奠我那悲催的基础知识)
- C语言中的static
- Sub-process /usr/bin/dpkg returned an error code (1)错误解决办法
- 路由器的IP和上网IP的区别是啥?相互有什么关系?
- 永久的IP标识(persistent IPlabel)
- 演练:在后台运行操作
- TI达芬奇技术学习计划(转)
- Outlook时间管理简介
- 软件开发中常见的十大系统瓶颈
- 肯·汤普逊-C语言创始人
- HOG特征
- Package does not match intended download的问题解决方法
- dispatch_group_wait
- Android应用程序消息处理机制(Looper、Handler)分析