c#中使用BackgroundWorker的实现

  public partial class Form1 : Form

  {

  public Form1()

  {

  InitializeComponent();

  }

  private void btnStart_Click(object sender, EventArgs e)

  {

  if (bgWorker.IsBusy) //判断是否正在运行异步操作

  return;

  this.progressBar1.Maximum = 100; //设置进度条最大值

  this.btnStart.Enabled = false;

  this.btnStop.Enabled = true;

  bgWorker.RunWorkerAsync("11111"); //给业务传递参数,就是把前台的要处理的参数传递进去

  }

  public void bgWorker_DoWork(object sender, DoWorkEventArgs e)

  {

  //业务处理

  object s = e.Argument; //这的e.Argument就是上面传递的参数 11111

  for (int i = 0; i <= this.progressBar1.Maximum; i++)

  {

  if (bgWorker.CancellationPending) //此处关联的是btnStop_Click事件中的这个bgWorker.CancelAsync();如果这个触发了,那么就会停止。

  {

  e.Cancel = true;

  return;

  }

  else

  {

  bgWorker.ReportProgress(i, "222222"); //向bgWorker_ProgessChanged事件传递参数,第一个是进度的参数,第二个是你要处理业务的参数

  System.Threading.Thread.Sleep(1);

  }

  }

  }

  public void bgWorker_ProgessChanged(object sender, ProgressChangedEventArgs e)

  {

  //页面处理

  string state = (string)e.UserState;//接收上bgWorker.ReportProgress方法传递过来的参数userState

  this.progressBar1.Value = e.ProgressPercentage;

  this.label1.Text = "处理进度:" + Convert.ToString(e.ProgressPercentage) + "%";

  //label2.Text = e.ProgressPercentage.ToString();

  }

  public void bgWorker_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

  {

  if (e.Error != null)

  {

  MessageBox.Show(e.Error.ToString());

  return;

  }

  if (!e.Cancelled)

  this.label1.Text = "处理完毕!";

  else

  this.label1.Text = "处理终止!";

  }

  private void btnStop_Click(object sender, EventArgs e)

  {

  this.btnStart.Enabled = true;

  this.btnStop.Enabled = false;

  bgWorker.CancelAsync();

  }

  }