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.Tasks;

  using System.Windows.Forms;

  using System.IO;

  using System.Threading;

  namespace BackgroundWorkerDemo

  {

  public partial class FrmDemo : Form

  {

  //设置生成临时文件的路径

  static string strSaveDir = @"F:培训";

  public FrmDemo()

  {

  InitializeComponent();

  //显示后台操作的执行进度

  this.bgWork.WorkerReportsProgress = true;

  //可以取消后台正在执行的操作

  this.bgWork.WorkerSupportsCancellation = true;

  }

  ///

  /// 开始

  ///

  ///

  ///

  private void btn_Start_Click(object sender, EventArgs e)

  {

  if (Directory.Exists(strSaveDir) == false)

  {

  return;

  }

  btn_Start.Enabled = false;

  int count = Convert.ToInt32(this.txt_File.Text.ToString().Trim());

  //设置进度条

  this.proBar.Minimum = 0;

  this.proBar.Maximum = count;

  this.proBar.Value = this.proBar.Minimum;

  //开始执行异步线程,进行后台操作,给后台传递参数

  this.bgWork.RunWorkerAsync(count);

  }

  ///

  /// 后台操作要处理的任务代码

  ///

  ///

  ///

  private void bgWork_DoWork(object sender, DoWorkEventArgs e)

  {

  //获取从RunWorkerAsync()方法里面传递的参数的值

  int fileCount= Convert.ToInt32(e.Argument);

  Random rand = new Random();

  byte[] buffer = new byte[2048];

  for (int i = 0; i < fileCount; i++)

  {

  try

  {

  string strFileName = Path.Combine(strSaveDir, i.ToString() + ".tmp");

  using (var stream = File.Create(strFileName))

  {

  int n = 0;

  int maxByte = 8 * 1024 * 1024;

  while (n < maxByte)

  {

  rand.NextBytes(buffer);

  stream.Write(buffer, 0, buffer.Length);

  n += buffer.Length;

  }

  }

  }

  catch (Exception ex)

  {

  continue;

  }

  finally

  {

  //报告进度

  this.bgWork.ReportProgress(i + 1);

  Thread.Sleep(100);

  }

  //判断是否取消了后台操作

  if (bgWork.CancellationPending)

  {

  e.Cancel = true;

  return;

  }

  //设置返回值

  e.Result = 234;

  }

  }

  ///

  /// 更新前台界面进度条

  ///

  ///

  ///

  private void bgWork_ProgressChanged(object sender, ProgressChangedEventArgs e)

  {

  //获取异步任务的进度百分百

  int val = e.ProgressPercentage;

  this.label2.Text = string.Format("已经生成{0}个文件", val);

  //进度条显示当前进度

  this.proBar.Value = val;

  }

  ///

  /// 后台操作完成,向前台反馈信息

  ///

  ///

  ///

  private void bgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

  {

  btn_Start.Enabled = true;

  //用户取消操作(e.Cancelled==true,表示异步操作已被取消)

  if (e.Cancelled)

  {

  MessageBox.Show("用户取消后台操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

  }

  else

  {

  MessageBox.Show("操作完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

  //接收返回值

  int result = (int)e.Result;

  MessageBox.Show("返回值:" + result);

  }

  }

  ///

  /// 取消

  ///

  ///

  ///

  private void btn_Cancle_Click(object sender, EventArgs e)

  {

  //调用CancelAsync(),取消挂起的后台操作

  this.bgWork.CancelAsync();

  }

  }

  }