可见BackGroundWorker
有三个事件,事件间通过EventArgs
实现参数传递。有用到CancellationPending
属性判断取消。EvnentArgs
有很多属性:Cancel
、Argument
、Result
、ProgressPercentage
、UserState
属性等。
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; namespace BackGroundWorkDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.backgroundWorker1.WorkerReportsProgress = true; // 这两个属性也可以去控件的属性栏里面改 this.backgroundWorker1.WorkerSupportsCancellation = true; this.StartPosition = FormStartPosition.CenterScreen; } // Backgroundworker的三个事件 // [1]开始后台要执行的任务,可见参数都是通过 EventArgs 参数传递的。 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker bgw = sender as BackgroundWorker; int result = 0; for (int i = 1; i <= 100; i++) { if (bgw.CancellationPending) {// 如果取消操作 e.Cancel = true; // 把取消结果传出去,传给 RunWorkerComplete事件中。 return; } result += i;// 累加 bgw.ReportProgress(i, "已经完成了" + i.ToString() + "%"); // 报告进度,第二个参数是: UserState。传给 ProgressChanged 事件。 System.Threading.Thread.Sleep((int)e.Argument);//根据外部传入参数休眠,模拟计算耗时。 e.Result = result; // 把计算结果传出去 } } // [2]/汇报后台工作进展 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { this.progressBar1.Value = e.ProgressPercentage;// 显示百分比 this.lblProgressPercent.Text = e.UserState.ToString();// 显示进度条上面的百分信息 } // [3]后台任务完成 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled) { toolStripStatusLabel1.Text = "用户取消操作"; btnBegin.Enabled = false; return; } if (e.Error != null) { toolStripStatusLabel1.Text = e.Error.Message; return; } this.lblResult.Text = e.Result.ToString(); // 显示结果 this.btnBegin.Enabled = true; toolStripStatusLabel1.Text = "计算完成"; } // 开启任务 private void btnBegin_Click(object sender, EventArgs e) { lblResult.Text = "???"; lblResult.Refresh(); // 启动后台程序(参数argument传给休眠时间) backgroundWorker1.RunWorkerAsync(20); btnBegin.Enabled = false; toolStripStatusLabel1.Text = "稍等,正在计算…"; } // 取消 private void btnCancel_Click(object sender, EventArgs e) { backgroundWorker1.CancelAsync(); } // 关闭 private void btnClose_Click(object sender, EventArgs e) { this.Close(); } } }
运行效果: