在我的課上,我使用了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();
}