Using BackgroundWorker with Silverlight 2.0

 

A long time ago I wrote two articles on the asynchronous processing model in .NET 1.0 and .NET 2.0. This last part was mainly about the BackgroundWorker class for running things in the background.

This same model also works in Silverlight 2.0 (Beta 1). So if you need to do some heavy calculation or anything else taking a long time you should use the BackgroundWorker class.

Using the BackgroundWorker is easy, first create an instance of it:

BackgroundWorker worker = new BackgroundWorker();

Then set the DoWork event to do the "long" thing, for example here emulated with a simple sleepy loop:

worker.DoWork += 
  delegate(object sender, DoWorkEventArgs e)   {     DateTime start = DateTime.Now;     for (int i = 0; i < 100; i++)     {       Thread.Sleep(50);       worker.ReportProgress(i);     }      e.Result =        string.Format("Done, this took {0} sec",        DateTime.Now.Subtract(start).TotalSeconds);   };

This worker reports on progress using the ReportProgress method. We need to do this because in the DoWork event it is forbidden to touch any of the controls. It is allowed on the ProgressChanged event:

worker.WorkerReportsProgress = true; worker.ProgressChanged += 
  delegate (object sender, ProgressChangedEventArgs e)   {     timer.Text = string.Format("{0}% done", e.ProgressPercentage);     progress.Value = e.ProgressPercentage;   } 

Also note that the last line of the DoWork event sets e.Result. This is used to pass the result to the event which handles the completion of the work, the RunWorkerCompleted event:

worker.RunWorkerCompleted +=    delegate (object sender, RunWorkerCompletedEventArgs e)   {     timer.Text = (string)e.Result;   }; 

 

Again you're not allowed to change controls in the DoWork event, so if you want to update controls when the calculation is done, you do this in the RunWorkerCompleted event.

The BackgroundWorker also supports canceling the long running task, and handling error in the correct way. More in above mentioned articles.

A complete sample project about using the backgroundworker can be found here.