Safe Multithreading with the BackgroundWorker Component


In the physical world, two workers are twice as productive as one. In the programming world, using additional threads safely can increase an application's productivity and add a depth and richness that help the user to be more productive too. The drawback has been that multi-threaded applications typically have been harder to write and debug. This is still true to some extent; but with .NET, multithreading is getting easier to use.
Early editions of .NET introduced thread pools, and .NET 2.0 introduces the BackgroundWorker component. The BackgroundWorker component permits you to incorporate additional worker threads, and it isn't much harder to use then the old standby, the Timer component.
This article demonstrates how to use the BackgroundWorker component safely, including how to marshal control from the worker thread back to the Windows Forms thread.

Implementing the DoWorkEventHandler

Because the BackgroundWorker class is a component, you can drag and drop it onto a Windows Form or UserControl and wire up event handlers visually. If you don't have a form or UserControl, you can declare and create an instance of the BackgroundWorker and bind its event properties with code.
The BackgroundWorker component is defined in the System.ComponentModel namespace. To use the BackgroundWorker, you can add an Imports statement or use the namespace in the declaration and initialization statement. Here is an example:
  1. Dim worker as System.ComponentModel.BackgroundWorker
  2. worker = new System.ComponentModel.BackgroundWorker
The worker thread is expressed as a delegate wired to the BackgroundWorker.DoWork event property. The following is the signature of the delegate (event handler) for the DoWork property:
  1. Sub DoWork(Sender As Object, _
  2. e As System.ComponentModel.DoWorkEventArgs)
Any subroutine with the two argument types in the order shown can be assigned to the DoWork event property. The BackgroundWorker component also has a ProgressChanged event property, and you can signal the relative progress of the background thread by wiring an event handler to the ProgressChanged event. The following is the signature for ProgressChanged:
  1. Sub ProgressChanged(sender As Object, _
  2. e As System.ComponentModel.ProgressChangedEventArgs)
Listing 1 shows how to create an instance of the BackgroundWorker component and wire up DoWork and ProgressChanged in the Form's OnLoad event.
Listing 1: Create and Wire Up DoWork and ProgressChanged Events for BackgroundWorker Component
  1. Private worker As BackgroundWorker
  2.  
  3. Private Sub Form1_Load(ByVal sender As System.Object, _
  4. ByVal e As System.EventArgs) Handles MyBase.Load
  5.  
  6. worker = New BackgroundWorker()
  7. worker.WorkerReportsProgress = True
  8. AddHandler worker.DoWork, New _
  9. DoWorkEventHandler(AddressOf OnWork)
  10. AddHandler worker.ProgressChanged, _
  11. New ProgressChangedEventHandler(AddressOf OnProgressChanged)
  12.  
  13. End Sub

Running the Worker Thread

To start the worker thread, you invoke the BackgroundWorker.RunWorkerAsync method. This example adds ProgressBar to a form and uses a button to simulate an event that initiates the background worker process. The following snippet demonstrates how to start the background thread:
  1. Private Sub Button1_Click(ByVal sender As System.Object, _
  2. ByVal e As System.EventArgs) Handles Button1.Click
  3. worker.RunWorkerAsync()
  4. End Sub
Figure 1 shows the simple example Form. The ProgressBar shown will be updated indirectly by an event the BackgroundWorker component raises.
Figure 1: Example Form with ProgressBar

Safe Multithreading in Windows Forms

At this point, you have enough code to use multithreading. To interact with Windows Forms controls and control properties without crashing the program, however, you have to use delegates a bit more.
Presently, .NET is not designed to safely and reliably manipulate Windows Forms controls across thread boundaries. To correct this deficiency, you have to marshal any data or interactions from the background thread to the same thread on which the Windows Forms and controls are. You do this with a delegate. For example, if you want to update the ProgressBar from the BackgroundWorker's ProgressChanged event handler, you need to define a delegate with arguments mirroring the data you want to pass and use the Form's Invoke method. Call Invoke with the delegate address and data—this is referred to as marshalling.
Listing 2 shows the implementation of BackgroundWorker's ProgressChanged event handler, as well as the delegate definition and the additional event handler used to update the ProgressBar. OnProgressChanged responds to the ProgressChanged event and the Invoke method call uses the custom ChangeProgressBarHandler to marshal data to the Form's thread.
Listing 2: Implementation of BackgroundWorker's ProgressChanged Event Handler
  1. Private Sub OnProgressChanged(ByVal sender As Object, _
  2. ByVal e As ProgressChangedEventArgs)
  3. Invoke(New ChangeProgressBarHandler( _
  4. AddressOf ChangeProgressbar), e.ProgressPercentage)
  5. End Sub
  6.  
  7. Private Delegate Sub ChangeProgressBarHandler(ByVal percentage _
  8. As Integer)
  9.  
  10. Private Sub ChangeProgressBar(ByVal percentage As Integer)
  11. ProgressBar1.Value = percentage
  12. End Sub
Listing 3 provides the complete code set for the example, showing the OnWork event handler that represents background work.
Listing 3: All the Custom Code for the Sample Form Shown in Figure 1
  1. Imports System.ComponentModel
  2.  
  3. Public Class Form1
  4.  
  5. Private worker As BackgroundWorker
  6.  
  7. Private Sub Form1_Load(ByVal sender As System.Object, _
  8. ByVal e As System.EventArgs) Handles MyBase.Load
  9.  
  10. worker = New BackgroundWorker()
  11. worker.WorkerReportsProgress = True
  12. AddHandler worker.DoWork, New _
  13. DoWorkEventHandler(AddressOf OnWork)
  14. AddHandler worker.ProgressChanged, _
  15. New ProgressChangedEventHandler(AddressOf OnProgressChanged)
  16. End Sub
  17.  
  18. Private Sub OnWork(ByVal sender As Object, _
  19. ByVal e As DoWorkEventArgs)
  20. Dim I As Integer
  21. For I = 1 To 100
  22. System.Threading.Thread.Sleep(10)
  23. worker.ReportProgress(I)
  24. Next
  25. End Sub
  26.  
  27. Private Sub OnProgressChanged(ByVal sender As Object, _
  28. ByVal e As ProgressChangedEventArgs)
  29. Invoke(New ChangeProgressBarHandler( _
  30. AddressOf ChangeProgressbar), e.ProgressPercentage)
  31. End Sub
  32.  
  33. Private Delegate Sub ChangeProgressBarHandler(ByVal _
  34. percentage As Integer)
  35.  
  36. Private Sub ChangeProgressBar(ByVal percentage As Integer)
  37. ProgressBar1.Value = percentage
  38. End Sub
  39.  
  40. Private Sub Button1_Click(ByVal sender As System.Object, _
  41. ByVal e As System.EventArgs) Handles Button1.Click
  42. worker.RunWorkerAsync()
  43. End Sub
  44. End Class
OnWork really only shows that the ProgressBar is being updated, and interacting with the Form will clearly demonstrate that the Form's thread is available—for example, the form is refreshed if you move it around. That said, the sample application does demonstrate all of the preparation and steps necessary to use additional threads. All that remains for you to do is find useful work for the background thread.
Tip: If you want to see the various threads the sample application in Listing 3 uses, set a breakpoint in the code. When the breakpoint is reached, select Debug|Windows|Threads.