这是工作代码。我什至已经完成了这个。 e.cancel = true 后,DoWork 再次运行,进入 while 循环,再次将 e.Cancel 设置为 true,然后退出该函数,不再运行 Completed 函数。
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
//While the song is not over
while (!worker.CancellationPending )
{
if (progressBar1.Value == progressBar1.Maximum)
{
e.Cancel = true;
return;
}
else
{
//Keep ticking the progress bar one second
worker.ReportProgress(0);
Thread.Sleep(1000);
}
}
e.Cancel = true;
return;
}
这是取消 worker 的代码。 WaitOne() 将阻塞,直到它收到来自 RunWorkerCompleted 的信号。
if (this.backgroundWorker2.IsBusy)
{
this.backgroundWorker2.CancelAsync();
_resetEvent.WaitOne();
}
编辑:请注意,我已经完成了这个 VV
backgroundWorker2.RunWorkerCompleted += backgroundWorker2_RunWorkerCompleted;
backgroundWorker2.WorkerSupportsCancellation = true;
最佳答案
你设置了吗
BackgroundWorker.WorkerSupportsCancellation = true
?
关于c# - e.cancel = true 后后台worker不会运行 "RunWorkerCompleted";,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13908271/