Implement threads in your Windows Forms program with BackgroundWorker. Intensive tasks needs to be done on another thread so that the UI doesn't freeze. Implement the code and design as easily as possible. You want to post messages and update the user interface when the task is done.
On the image, you will see the Visual Studio 2008 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.
Those 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.
It 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.
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 processor-intensive
}
}
}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.
| This object in code | Is used like this in real programs |
| 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 parameter); | Called to start a process on the worker thread. |
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. Here is some example code.
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; }
}Put 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.
/// <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;
}Go 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.
/// <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)
//
}You probably know more than you think. BackgroundWorker has a name that might indicate it is more complex (or hard, like 'work') 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.
Always use threads when you have a long-running computation in the background. Prefer ThreadPool when you need many threads. Threads aren't as great for I/O operations, as most computers can't multithread disk accesses as well. With the era of multicore systems, we need threads and BackgroundWorker is an excellent shortcut.