使用BackGroundWork处理大批量数据并用进度条显示进度_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 使用BackGroundWork处理大批量数据并用进度条显示进度

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

 2013/8/27 23:03:34  蒋叶湖  博客园  我要评论(0)
  • 摘要:微软提供的backgroundWorker是个非常好的用于异步操作的组件。下面就简单说明一下使用该组件实现异步处理大批量数据并用进度条显示处理进度的功能,并提供取消功能。通过在主窗体点击按钮弹出进度条模式窗体,提示用户数据处理进度。效果图如下:调用代码:privatevoidbutton1_Click(objectsender,EventArgse){this.backgroundWorker1.RunWorkerAsync()
  • 标签:使用 进度条 数据
   

   微软提供的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();

        }

 

完整源码请进入群下载

发表评论
用户名: 匿名