C#中Backgroundworker与Thread的区别

  public partial class MainWindow : Window

  {

  private BackgroundWorker m_BackgroundWorker;// 申明后台对象

  public MainWindow()

  {

  InitializeComponent();

  m_BackgroundWorker = new BackgroundWorker(); // 实例化后台对象

  m_BackgroundWorker.WorkerReportsProgress = true; // 设置可以通告进度

  m_BackgroundWorker.WorkerSupportsCancellation = true; // 设置可以取消

  m_BackgroundWorker.DoWork += new DoWorkEventHandler(DoWork);

  m_BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);

  m_BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);

  m_BackgroundWorker.RunWorkerAsync(this);

  }

  void DoWork(object sender, DoWorkEventArgs e)

  {

  BackgroundWorker bw = sender as BackgroundWorker;

  MainWindow win = e.Argument as MainWindow;

  int i = 0;

  while ( i <= 100 )

  {

  if (bw.CancellationPending)

  {

  e.Cancel = true;

  break;

  }

  bw.ReportProgress(i++);

  Thread.Sleep(1000);

  }

  }

  void UpdateProgress(object sender, ProgressChangedEventArgs e)

  {

  int progress = e.ProgressPercentage;

  label1.Content = string.Format("{0}",progress);

  }

  void CompletedWork(object sender, RunWorkerCompletedEventArgs e)

  {

  if ( e.Error != null)

  {

  MessageBox.Show("Error");

  }

  else if (e.Cancelled)

  {

  MessageBox.Show("Canceled");

  }

  else

  {

  MessageBox.Show("Completed");

  }

  }

  private void button1_Click(object sender, RoutedEventArgs e)

  {

  m_BackgroundWorker.CancelAsync();

  }

  }