态度决定高度、企图决定版图、格局决定结局

导航

dotnet中一个重要组件-BackgroundWorker

最近一直在看wse3.0,从一个例子中偶然的收获。虽然通过后台操作,从而减少用户交互时的“僵硬”体验一直是每个程序员的追求,在今天这样ajax的时代里面更加显的重要。一切为了用户,一切为了更丰富愉快的体验。本文并不是ajax相关的东东。伟大的BackgroundWorker!

BackgroundWorker 类允许您在单独的专用线程上运行操作。耗时的操作(如下载和数据库事务)在长时间运行时可能会导致用户界面 (UI) 似乎处于停止响应状态。如果您需要能进行响应的用户界面,而且面临与这类操作相关的长时间延迟,则可以使用 BackgroundWorker 类方便地解决问题。

您必须非常小心,确保在 DoWork 事件处理程序中不操作任何用户界面对象。而应该通过 ProgressChangedRunWorkerCompleted 事件与用户界面进行通信

使用方式:
1。给组件注册事件处理方法:

           //正式做事情的地方 
           backgroundWorker1.DoWork +=
                new DoWorkEventHandler(backgroundWorker1_DoWork);

            //任务完称时要做的,比如提示等等            
            backgroundWorker1.RunWorkerCompleted +=
                new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            //任务进行时,报告进度                     
            backgroundWorker1.ProgressChanged +=
                new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);

2。添加具体事件处理方法

DoWork 调用 RunWorkerAsync 时发生。
ProgressChanged 调用 ReportProgress 时发生。
  RunWorkerCompleted 当后台操作已完成、被取消或引发异常时发生。





 1//这个例子没有做什么事情,完全是看看效果而已,但同时有个大问题,我也不知道为什么,没有去除僵硬情况。
 2namespace BackgroundWorkerTest
 3{
 4    public partial class Form1 : Form
 5    {
 6        public Form1()
 7        {
 8            InitializeComponent();
 9            InitialzeBackgroundWorker();
10        }

11
12        private void InitialzeBackgroundWorker()
13        {
14            this.backgroundWorker1.DoWork+=new DoWorkEventHandler(backgroundWorker1_DoWork);
15            this.backgroundWorker1.ProgressChanged+=new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
16            this.backgroundWorker1.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
17        }

18
19
20        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
21        {
22            MessageBox.Show("Completly");
23        }

24
25        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
26        {
27            this.progressBar1.Value = e.ProgressPercentage;
28        }

29        private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e)
30        {
31            e.Result = ComputeFibonacci(this.backgroundWorker1, e);
32        }

33
34        private int ComputeFibonacci(object sender, DoWorkEventArgs e)
35        {
36           
37            for (int i = 0; i < 100000; i++)
38            {
39                if (this.backgroundWorker1.CancellationPending)
40                {
41                    e.Cancel = true;
42                    
43                }

44                else
45                {
46                    this.backgroundWorker1.ReportProgress(i);                   
47                }

48                
49            }

50            return 0;
51
52        }

53
54
55        private void button1_Click(object sender, EventArgs e)
56        {
57            this.backgroundWorker1.RunWorkerAsync();
58        }

59
60        private void button2_Click(object sender, EventArgs e)
61        {
62            this.backgroundWorker1.CancelAsync();
63        }

64    }

65}

给出另一种使用:继承BackgroundWorker:

namespace UploadWinClient
{
    
/// <summary>
    
/// Contains common functionality for the upload and download classes
    
/// This class should really be marked abstract but VS doesn't like that because it can't draw it as a component then :(
    
/// </summary>

    public class FileTransferBase : BackgroundWorker
    
{
public FileTransferBase()
        
{
            
base.WorkerReportsProgress = true;
            
base.WorkerSupportsCancellation = true;            
        }

protected override void Dispose(bool disposing)
        
{
            
if(this.HashThread != null && this.HashThread.IsAlive)
                
this.HashThread.Abort();

            
base.Dispose(disposing);
        }


        
protected override void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
        
{
            
if(this.HashThread != null && this.HashThread.IsAlive)
                
this.HashThread.Abort();
            
            
base.OnRunWorkerCompleted(e);
        }


        
protected override void OnDoWork(DoWorkEventArgs e)
        
{
            
// make sure we can connect to the web service.  if this step is not done here, it will retry 50 times because of the retry code
            this.WebService.Ping();
            
base.OnDoWork(e);
        }

}
//截取的部分代码。
//从中给出我们要override的一些方法


BackgroundWorker在长时间的webservices中特别有用。





posted on 2006-07-05 10:25  flyingchen  阅读(2960)  评论(1编辑  收藏  举报