在我的课上,我使用了BackgroundWorker。在某些时候,我需要取消正在进行的异步操作,并立即启动另一个操作。代码如下。我不确定的一件事是如果在我将lambda分配给RunWorkerCompleted事件之前工作人员完成,可能发生的竞争条件。如果发生这种情况,我的lambda将永远不会被调用。代码中的评论显示了这个地方。有关如何处理此问题的任何意见?如何处理这种竞争条件?
感谢 康斯坦丁
if (this.worker.IsBusy)
{
RunWorkerCompletedEventHandler f = null;
f = (s, v) =>
{
this.RunWorkerCompleted -= f;
this.worker.RunWorkerAsync();
};
// what if worker completes right before the following statement?
this.worker.RunWorkerCompleted += f;
this.worker.CancelAsync();
}
else
{
this.worker.RunWorkerAsync();
}