C# BackgroundWorker Tutorial

Dot Net Perls
BackgroundWorker screenshot

You want to implement threads in your Windows Forms program with BackgroundWorker. Intensive tasks need to be done on another thread so that the UI doesn't freeze. Post messages and update the user interface when the task is done. Here is a tutorial for getting a BackgroundWorker functioning in your program, using the C# programming language.

Steps

On the image, you see the Visual Studio designer view. The fly-out panel is the Toolbox, and it contains links for all kinds of controls. It also contains the BackgroundWorker link, which we can use in the following steps.

First step. First, click on BackgroundWorker. You will need to double-click on BackgroundWorker link in the Toolbox. Next, look at the gray bar near the bottom of your window; a BackgroundWorker will appear there.

Second step. Next, highlight backgroundWorker1, clicking on the backgroundWorker1 item in the gray bar on the bottom. Now, look at Properties panel, which is usually on the right.

Third step. Third, look for the lightning bolt. You will see a lightning bolt icon in the Properties pane. This is Microsoft's icon for events. BackgroundWorker is event-driven, so this is where we will make the necessary events to use it.

Fourth step. The fourth step is to double-click on DoWork. Sorry, but we have to get working now. Double-click on DoWork, which will tell Visual Studio to make a new "work" method. In this method, you will put the important, processor-intensive stuff.

BackgroundWorker in Visual Studio

Description. The circles show the tray at the bottom where the backgroundWorker1 icon is, and the Properties panel on the right. What the lightning bolt is good for is easily adding events to the BackgroundWorker. This UI is far better than trying to type the methods in manually.

Add DoWork

The DoWork method is like any other event handler. Here we must look at the C# view of your file, where we will see the DoWork method. You should see that the backgroundWorker1_DoWork event is generated when you double-click on DoWork. For testing, let's add a Thread.Sleep command there. The Thread.Sleep method will pause the execution of the BackgroundWorker, but does not consume the entire CPU.

Sleep Method Pauses Programs
Example that shows DoWork event handler [C#]

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
	{
	    Thread.Sleep(1000); // Very time-consuming.
	}
    }

}

Properties

Property (Icon copyright Microsoft)

This is not an exhaustive list, but I want to emphasize the Argument, Result, and the RunWorkerAsync methods. These are properties of BackgroundWorker that you absolutely need to know to accomplish anything. I show the properties as you would reference them in your code.

DoWorkEventArgs e Contains e.Argument and e.Result, so it is used to access those properties.

e.Argument Used to get the parameter reference received by RunWorkerAsync.

e.Result Check to see what the BackgroundWorker processing did.

backgroundWorker1.RunWorkerAsync(object); Called to start a process on the worker thread.

Execute code

You can add instructions to the BackgroundWorker by adding arguments and return values. Here I show how you must add arguments, invoke the BackgroundWorker, and then receive the results of the thread. You should know enough about threads to know that you can't change variables from multiple threads at once and not have bugs.

Example that shows RunWorkerAsync call [C#]

public partial class Form1 : Form
{
    public Form1()
    {
	InitializeComponent();

	//
	// Example argument object
	//
	TestObject test = new TestObject
	{
	    OneValue = 5,
	    TwoValue = 4
	};
	//
	// Send argument to our worker thread
	//
	backgroundWorker1.RunWorkerAsync(test);
    }
}

/// <summary>
/// The test class for our example.
/// </summary>
class TestObject
{
    public int OneValue { get; set; }
    public int TwoValue { get; set; }
}

An example argument is created. TestObject in the above code is an example object. You will have something more important and complex in your program. The syntax above is just C# collection initializer syntax.

It can be called anywhere. You can call RunWorkerAsync anywhere in your code. This example uses a constructor, but that isn't important to the example.

Implement DoWork

You can implement DoWork by putting your expensive code in it. Then, use the DoWorkEventArgs in its body and as its result. Here we hook up the arguments and results from the RunWorkerAsync call. Remember, the TestObject was passed to RunWorkerAsync, and that is received as e.Argument. We also have to cast, as I show in the following code.

Example that shows DoWork event handler [C#]

/// <summary>
/// Where we do the work in the program (the expensive slow stuff).
/// </summary>
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    //
    // e.Argument always contains whatever was sent to the background worker
    // in RunWorkerAsync. We can simply cast it to its original type.
    //
    TestObject argumentTest = e.Argument as TestObject;

    //
    // Boring....
    //
    Thread.Sleep(10000);

    argumentTest.OneValue = 6;
    argumentTest.TwoValue = 3;

    //
    // Now, return the values we generated in this method.
    // Always use e.Result.
    //
    e.Result = argumentTest;
}

RunWorkerCompleted

Lightning bolt

You can use the RunWorkerCompleted event handling by going to the lightning bolt in the designer by clicking on the backgroundWorker1 icon in the tray. Now double click in RunWorkerCompleted. You will get some autogenerated code that looks just like this. Put the argument receiving code in this method.

Example that shows RunWorkerCompleted event handler [C#]

/// <summary>
/// This is on the main thread, so we can update a TextBox or anything.
/// </summary>
private void backgroundWorker1_RunWorkerCompleted(object sender,
    RunWorkerCompletedEventArgs e)
{
    //
    // Receive the result from DoWork, and display it.
    //
    TestObject test = e.Result as TestObject;
    this.Text = test.OneValue.ToString() + " " + test.TwoValue.ToString();

    //
    // Will display "6 3" in title Text (in this example)
    //
}

Tips

Programming tip

You probably know more than you think about the BackgroundWorker class. BackgroundWorker has a name that might indicate it is more complex than it really is. There are many more details about threading and abort calls, but once you understand that BackgroundWorker is just a structural "overlay" to threads in Windows Forms, it is quite intuitive. Here are the steps again:

First, call RunWorkerAsync with an argument. You can pass any argument to this method on BackgroundWorker, including null. It simply must inherit from object, which everything does.

Second, custom processing is run. Your expensive code is executed in the DoWork method. Insert pause here as your program does its calculations.

Third, it finishes. When your processing is done, RunWorkerCompleted is called. In this method, you receive the result. In this way, your BackgroundWorker object modifies an object on another thread, and you receive it when it is done.

ProgressBar

It is an excellent idea to use the ProgressBar control with your BackgroundWorker. This site has a detailed tutorial on how to use the ProgressBar with a BackgroundWorker. Please consult the selected article.

ProgressBar Example (Windows Forms)

Summary

The C# programming language

We saw how you can implement the code for a BackgroundWorker control in Windows Forms using the C# language. Generally, you should prefer ThreadPool when you need many threads. Threads aren't always useful, such as for I/O operations, which many computers can't multithread as well. With the era of multiple processor systems, we need threads and BackgroundWorker is an excellent shortcut.

Thread Overview