C#中backgroundWorker类的用法详解

  using System;

  using System.Collections.Generic;

  using System.ComponentModel;

  using System.Data;

  using System.Drawing;

  using System.Linq;

  using System.Text;

  using System.Threading;

  using System.Threading.Tasks;

  using System.Windows.Forms;

  namespace Delegate3

  {

  public partial class Form1 : Form

  {

  public Form1()

  {

  InitializeComponent();

  }

  private void button1_Click(object sender, EventArgs e)

  {

  //启动异步调用方法

  //调用RunWorkerAsync()方法,会触发DoWork事件

  this.backgroundWorker2.RunWorkerAsync();

  }

  private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)

  {

  backgroundWorker2.WorkerReportsProgress = true;

  for (int i = 1; i <= 100; i++)

  {

  //这里判断一下是否用户要求取消后台进行,并可以尽早退出。

  //可以通过调用CancelAsync方法设置CancellationPending的值为false

  if (backgroundWorker2.CancellationPending)

  {

  backgroundWorker2.ReportProgress(i, String.Format("{0}%,操作被用户申请中断", i));

  }

  //调用 ReportProgress 方法,会触发ProgressChanged事件

  backgroundWorker2.ReportProgress(i, String.Format("{0}%", i));

  System.Threading.Thread.Sleep(10);

  }

  }

  private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)

  {

  this.progressBar1.Value = e.ProgressPercentage;

  this.label1.Text = e.UserState.ToString();

  this.label1.Update();

  }

  private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

  {

  //这是结束后做的事情

  MessageBox.Show("完成");

  }

  }

  }