[2.0] Cancelling Backgroundworker operation
In playing around with the BackgroundWorker, searching for examples on how to cancel it, I have come across this:
c# Code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0 ; i < 100 ; i++)
{
lock (backgroundWorker1)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
break;
}
}
System.Threading.Thread.Sleep(100);
backgroundWorker1.ReportProgress(0, i);
}
}
The code is only doing some pointless loop, but my question is - Is the 'lock' operation necessary? Could reading the CancellationPending property at the same time CancelAsync() is called without locking the worker object cause a problem perhaps?
I haven't seen this used anywhere else in the other examples I have found, so just looking for some opinions.
Thanks.
Re: [2.0] Cancelling Backgroundworker operation
I can't think of any issue that might arise without the lock.