I just had my first opportunity to use the BackgroundWorker object, and I must say I’m very impressed.

Part of creating a user interface is separating the work from the UI thread, so that the UI can remain responsive and report progress while a long operation is running.  This isn’t rocket science, but it is a bit of tedious development that every Windows Forms developer has had to learn how to do.  Not anymore.

Let’s say you want to count to a billion, on a background thread.  Here’s how you’d do it:

  1. Drop the BackgroundWorker object from the Toolbox onto your form.
  2. Add a handler for the DoWork event (double-click on DoWork in the Properties for your BackgroundWorker object)
  3. Call or write your code in the DoWork handler.
  4. When you want to run your asynchronous operation, call the backgroundWorker.RunWorkerAsync() method.

That’s it – no messing with threading or locking, it’s all handled by the BackgroundWorker object. 

The only thing that would have made it easier to implement background operations would have been supplying a standard progress dialog – you’ll have to implement that yourself.  Reporting progress is also handled through the BackgroundWorker object – in your worker thread you call ReportProgress, and on the main thread handle the ProgressChanged event.