Monday, April 23, 2007

Background Worker Class in .NET

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

and here is an example how you can do this:

Step 1: Create an instance of BackgroundWorker class:

private BackgroundWorker bw = new BackgroundWorker();

Step 2: Define DoWorkEventHandler and RunWorkerCompleted events before Page_Render events :

protected override void OnPreLoad(EventArgs e)
{
bw.DoWork += new DoWorkEventHandler(bw_DoWork);

bw.RunWorkerAsync();

bw.RunWorkerCompleted += new
RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

}

void bw_DoWork(object sender, DoWorkEventArgs de)
{
// Do your background work here
}

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
BackgroundWorker bgworker = sender as BackgroundWorker;
// Finalization of your backgroundworker
}

Step 4: Also set Async="true" on your aspx page.

Thats it your background worker instance is ready to work.
To read more about BackGroundWorker class go to this link

No comments:

Post a Comment