TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

VS2005: System.ComponentModel.BackgroundWorker

Visual Studio 2005 has a WinForms control called BackgroundWorker that let’s you fire off an asynchronous process on background thread and supports cancellation, progress reporting, and other events. All you have to do is drag and drop the control on your Web Form and you are ready to rock after wiring up a few simple events…

 

private void buttonRunBackgroundWorker_Click(object sender, EventArgs e)

{

    this.backgroundWorker1.WorkerReportsProgress = true;

    this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);

    this.backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);

    this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);

 

    int countTo = 100;

    this.backgroundWorker1.RunWorkerAsync(countTo);

}

 

void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

{

    int countTo = (int)e.Argument;

    for (int i = 1; i < countTo; i++)

    {

        System.Threading.Thread.Sleep(100);

        backgroundWorker1.ReportProgress(i);

    }

}

 

void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)

{

    this.progressBar1.Value = e.ProgressPercentage;

}

 

void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

    MessageBox.Show("Done!");

}

 

As you can see in this simple example, the button click event wires up the DoWork, ProgressChanges, and RunWorkerCompleted events. The DoWork event is where the background work takes place. As the loop fires, the background worker reports “progress” to the UI thread via backgroundWorker1_ProgressChanged and likewise fires the backgroundWorker1_RunWorkerCompleted when the background task is completed (or cancelled or if an Exception is thrown).


Digg!

posted on Friday, November 26, 2004 12:07 PM

Feedback

No comments posted yet.