In MSDN article about BackgroundWorker.CancelAsync method, there is a caution which says:
Be aware that your code in the
DoWorkevent handler may finish its
work as a cancellation request is being made, and your polling loop
may missCancellationPendingbeing set to true. In this case,
theCancelledflag of
System.ComponentModel.RunWorkerCompletedEventArgsin your
RunWorkerCompletedevent handler will not be set to true, even
though a cancellation request was made. This situation is called a
race condition and is a common concern in multithreaded programming.
What is the correct and good solution to avoid this race condition?
Here is my sample code, that provokes the apperance of this condition:
public partial class MainWindow : Window
{
BackgroundWorker bW;
int bWsCount = 0;
public MainWindow()
{
InitializeComponent();
}
private void Window_MouseMove(object sender, MouseEventArgs e)
{
if (bW != null)
bW.CancelAsync();
bW = new BackgroundWorker();
bW.WorkerSupportsCancellation = true;
bW.DoWork += new DoWorkEventHandler(bW_DoWork);
bW.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bW_RunWorkerCompleted);
bW.RunWorkerAsync(0);
bWsCount++;
labelBackgroundWorkersCount.Content = bWsCount;
}
void bW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if (e.Cancelled || worker.CancellationPending)
{
bWsCount--;
labelBackgroundWorkersCount.Content = bWsCount;
}
else
worker.RunWorkerAsync(1000);
}
void bW_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
int sleepDuration = Convert.ToInt32(e.Argument);
if (worker.CancellationPending) { e.Cancel = true; return; }
Thread.Sleep(sleepDuration);
if (worker.CancellationPending) { e.Cancel = true; return; }
}
}
There is no way to avoid it, not every threading problem has a solution. These things can be reasoned out when you push them to the extreme. Imagine the code in your UI thread calls CancelAsync() a nanosecond before the worker thread completes. Just as the thread is executing its last machine code instruction. Clearly there’s no possible way this could be detected by the thread. Nor is there any possible way for the UI thread to see that the thread is on its last instruction.
This is not a real problem, just keep it in mind when you write your RunWorkerCompleted event handler. If the e.Cancelled property is false then the worker completed anyway. If necessary, you can simply && it with another bool that you set to true when you call CancelAsync(). Roughly:
Please do keep in mind that this not just a race in code. The far more practical problem is that this is a race in the user’s brain as well. With the failure mode that everything completes normally a millisecond before the user clicks the Cancel button.
So as far as the user knows, the operation was canceled when in fact it was not. This can have unpleasant consequences, ones you’ll have to deal with by telling the user what really happened. In which case it really doesn’t make any sense to use the code snippet, it will work just as well if you only cancel the operation and allow it to complete anyway.