Backgroundworker取消时应该用的有关代码:
CancelAsync方法是在前台主线程用的,CancellationPending属性是在后台子线程用的。实际的使用方式应该是这样的:
1.要取消异步操作,一般来说是在窗体中点击“取消”按钮,在“取消”按钮的单击事件中触发CancelAsync方法
private void btn_Stop_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync(); //提交取消命令,但还未取消
}
2.这时,CancellationPending由false变为true
3.再在DoWork事件里获取CancellationPending,依据它来处理后台任务,比如说直接return;
static void bw_DoWork(object sender, DoWorkEventArgs e)
{ //判断是否取消操作
if (bw.CancellationPending)
{
e.Cancel = true; //这里才真正取消
return;
}
}
4.最后完成时判断
static void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
Console.WriteLine("You cancelled!");
else if (e.Error != null)
Console.WriteLine("Worker exception: " + e.Error.ToString());
else
{
Console.WriteLine("Complete - " + e.Result); // 从DoWork
}
}