Threading made easy with the BackGroundWorker Class
Posted
Tuesday, December 14, 2004 11:04 AM
by
C-Dog's .NET Tip of the Day
The BackGroundWorker class makes it easy to execute an operation on a seperate, dedicated thread. In the past, creating new threads for simple background operations could prove to be quite troublesome. The BackGroundWorker class makes it easy.
To set up a BackGroundWorker simply add an event handler for the DoWork event. You can put your long, time-consuming operations inside that event. When you are ready to start the operation, simply call the RunWorkerAsync method. The ProgressChanged event can be used to notify your application of any progress that has occurred. Lastly, the RunWorkerCompleted method will fire when the operation has completed.
// Set up the BackgroundWorker object by
// attaching event handlers
protected void InitializeBackgoundWorker()
{
backgroundWorker1.DoWork +=
new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
// launch the aync process on a button click event
protected void Button_Click(System.Object sender, System.EventArgs e)
{
// start the async process
backgroundWorker1.RunAsync();
}
// perform the long operation
protected void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
// do something
DoSomething();
}
// work completed event
protected void backgroundWorker1_RunWorkerCompleted(
object sender, RunWorkerCompletedEventArgs e)
{
// display completed message
ShowWorkCompletedMessage();
}
For more information, take a look at:
ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/cpref/html/T_System_ComponentModel_BackgroundWorker.htm
Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=214