In playing around with the BackgroundWorker, searching for examples on how to cancel it, I have come across this:
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?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); } }
I haven't seen this used anywhere else in the other examples I have found, so just looking for some opinions.
Thanks.



Reply With Quote
