使用BackGroundWork处理大批量数据并用进度条显示进度

 

   微软提供的backgroundWorker是个非常好的用于异步操作的组件。下面就简单说明一下使用该组件实现异步处理大批量数据并用进度条显示处理进度的功能,并提供取消功能。通过在主窗体点击按钮弹出进度条模式窗体,提示用户数据处理进度。效果图如下:

 

  

调用代码:

       private void button1_Click(object sender, EventArgs e)

        {

            this.backgroundWorker1.RunWorkerAsync();//运行backgroundWorker组件

          

 //显示进度条窗体

            ProcessForm form = new ProcessForm(this.backgroundWorker1);

            form.ShowDialog(this);

            form.Close();

      }

 

DoWork事件:在此事件中处理大批量数据
 
RunWorkerCompleted事件:无论是程序正常完成还是用户点击取消按钮,都会触发该事件
   private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            
if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            
else if (e.Cancelled)
            {
            }
            
else
            {
            }
        }

 

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker 
= sender as BackgroundWorker;

            
for (int i = 0; i < 100; i++)
            {
                
this.dtAll = DBOperator.GetDataTable("");//查询数据
                worker.ReportProgress(i);
                
if (worker.CancellationPending) //如果用户取消则跳出处理数据代码
                {
                    e.Cancel 
= true;
                    
break;
                }
            }
      }

 

 

 

 

ProcessForm窗体事件(进度条窗体)

  private BackgroundWorker backgroundWorker1;

        public ProcessForm(BackgroundWorker backgroundWorker1)

        {

            InitializeComponent();

            this.backgroundWorker1 = backgroundWorker1;

            this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);

            this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);

           

        }

 

        void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

        {

            this.Close();

        }

 

        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)

        {

            this.progressBar1.Value = e.ProgressPercentage;

        }       

 

        private void cancelButton1_Click(object sender, EventArgs e)

        {

            this.backgroundWorker1.CancelAsync();

            this.cancelButton1.Enabled = false;

            this.Close();

        }

 

完整源码请进入群下载

 

posted @ 2009-12-04 17:40    阅读(2662)  评论(2编辑  收藏  举报