in

Dot Net Mafia

Group site for developer blogs dealing with (usually) .NET, SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, and other Microsoft products, as well as some discussion of general programming related concepts.

This Blog

Syndication

Archives

Corey Roth [MVP]

A SharePoint MVP bringing you the latest time saving tips for SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, MOSS 2007, ASP.NET, LINQ, and Visual Studio 2012.

Threading made easy with the BackGroundWorker Class

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

2012 dotnetmafia.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems