C++开发博客CSDN

backgroundWorker使用

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
 
namespace Aisino.Fwkp.Wbjk.Forms
{
    public partial class DGJForm : Form
    {
        public DGJForm ()
        {
            Initialize();

 

           //
            // backgroundWorker1
            //
            this.backgroundWorker1.WorkerReportsProgress = true;
            this.backgroundWorker1.WorkerSupportsCancellation = true;
            this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
            this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
            this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);

        }

        private void DGJForm _Load(object sender, EventArgs e)
        {
            this.label1.Text = "";
            this.backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                int CheckTotal = DanJus.Rows.Count;

             

              for (int i = 0; i < DanJus.Rows.Count; i++)
            {
                if (backgroundWorker.CancellationPending)   //查看用户是否取消该线程
                {
                    break;
                }
                System.Threading.Thread.Sleep(400);  //为了显示,减速   
                backgroundWorker.ReportProgress((100 * (i + 1)) / CheckTotal, DanJuBH);
            }

                e.Result = CheckTotal;
            }
            catch (Exception ex)
            {
                    //.......

            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            this.backgroundWorker1.CancelAsync();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.label3.Visible = false;
            if (e.Cancelled)
            {
                MessageBox.Show("已取消");
            }
            else if (e.Error != null)
            {
                string msg = String.Format("发生错误: {0}", e.Error.Message);
                MessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            else
            {
                // 正常完成

            }
            this.Close();
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
            this.label1.Text = e.UserState.ToString();
        }
    }
}

posted @ 2012-11-19 14:37  纳凉亭子  阅读(316)  评论(0编辑  收藏  举报