通过一个demo来说一下backgroundworker的使用
上图使我们最终需要实现的效果,下来我们开始编码
在注释中已经写出属性的含义和绑定事件的含义。
BackgroundWorker backgroundWorker1;
backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
backgroundWorker1.WorkerReportsProgress = true;//能否报告进度更新
backgroundWorker1.WorkerSupportsCancellation = true;//能否支持异步取消
//绑定执行事件
backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
//绑定消息传递事件
backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
//绑定执行事件完成事件
backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
后台要执行的任务
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
for (int i = 0; i <= 100; i++)
{
if (bw.CancellationPending)//用户取消了操作CancellationPending会为true
{
//该结果会被传送到RunWorkerCompleted事件中
e.Cancel = true;
return;
}
//报告进度(同时触发ProgressChanged事件)
bw.ReportProgress(i,$"已经完成{i}%");
Thread.Sleep(Convert.ToInt32(e.Argument));
}
e.Result = "完成";
}
CancellationPending 是用户取消的标志,当用户调用CancelAsync()方法时CancellationPending 会为true。 e.Cancel = true;将结果会被传送到RunWorkerCompleted事件中(任务完成事件)
更新工作进展情况,在执行的任务重调用bw.ReportProgress()方法会触发该事件。
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//progressBar1是进度条控件,lblInfo是显示信息的lable
this.progressBar1.Value = e.ProgressPercentage;//显示百分比
lblInfo.Text = e.UserState.ToString();//显示文字信息。
}
e.ProgressPercentage是调用bw.ReportProgress()方法时的第一个参数,e.UserState为第二个参数
任务完成事件调用方法
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//e.Cancelled指示异步操作是否已被取消
//e.Error 指示异步操作期间发生的错误
//e.Result 获取异步操作结果的值,即DoWork事件中,Result设置的值。
if (e.Cancelled)
{
this.lblInfo.Text = "用户已经取消操作";
return;
}
if (e.Error != null)
{
this.lblInfo.Text = e.Error.Message;
return ;
}
this.lblInfo.Text = e.Result.ToString();
}
//开始按钮事件
private void btnStart_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync(50);
}
//结束按钮事件
private void btnCancel_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
backgroundWorker1.RunWorkerAsync(50); 开始执行任务,参数50可以在backgroundWorker1_DoWork方法中通过e.Argument取得,在backgroundWorker1_DoWork中有使用。 backgroundWorker1.CancelAsync();取消任务执行,实际上是修改了CancellationPending的值,false变为true 附上demo代码 链接:https://pan.baidu.com/s/1Q-tDzhzagU_kIujuwOCZhg 提取码:vn3q