如果要在执行过程中取消执行,则需要设置 WorkerSupportsCancellation = true, 并调用 CancelAsync();
在 DoWork事件中:
_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
...
if (worker.CancellationPending)
{
//这里e.Cancel要设置为true,否则RunWorkerCompleted事件中的e.Canncelled不会等于true
//如果在DoWork中抛出异常,那么RunWorkerCompleted事件中的e.Canncelled也不会等于true
e.Cancel = true;
break;
}
....
}
}
时间: 2024-10-13 15:08:52