Step-by-Step Instructions for using the BackgroundWorker
The purpose of the Background Worker
component is to allow you to easily perform a background task in a Windows Forms
application. Because Windows Forms have thread affinity, you can only
touch controls on the main UI thread. The Background Worker enables you to
cleanly run tasks on the appropriate thread without having to jump through too
many hoops. However, the API can seem confusing at times. So here is
a simple set of step-by-step instructions for using the component.
1.
Set the following BW property to True (design-time):
WorkerReportsProgress
2. Create DoWork event handler (design-time).
Double-click on DoWork in the event view of the property window.
Do your async stuff here
Do NOT touch any UI elements
Through each iteration call (i = percent complete):
backgroundWorker1.ReportProgress(i);
3. Create ProgressChanged event handler (design-time).
Double-click on ProgressChanged in the event view of the property window.
Access ProgressPercentage property of ProgressChangedEventArgs (e).
4. Create RunWorkerCompleted event handler (design-time).
Double-click on RunWorkerCompleted in the event view of the property window.
5. Call BW’s RunWorkerAsync method to fire DoWork event.
This kicks off the whole process by firing BW's DoWork event on a background thread (which comes from the Thread Pool).
backgroundWorker1.RunWorkerAsync();
6. To be able to cancel an async operation, perform the following steps:
Set the following BW property to True (design-time):
WorkerSupportsCancellationIn the loop within DoWork where you perform the background task,
check the BW’s CancellationPending property (runtime), then exit the method if it’s True.Call BW’s CancelAsync method, which in turn flips the CancellationPending flag to True: backgroundWorker1.CancelAsync();
That’s all there is to it! Now all you have to do is practice. :-)
Check out this working demo with sample code.