Executing Work on a Background Thread with Updates

1. Problem

You need to execute work in the background that provides updates on progress so that the UI can be responsive.

2. Solution

Use a background worker thread to execute work in the background.

3. How It Works

Silverlight 4 includes the System.Threading.Thread and System.Threading.ThreadPool classes as part of the .NET Framework for Silverlight. However, we recommend that you instead use the System.ComponentModel.BackgroundWorker
class to execute work in the background of the UI, such as loading or
saving data to isolated storage, accessing a remote service, etc. The BackgroundWorker
class provides a nice abstraction layer over the gory details of safely
synchronizing with the UI thread when using one of the lower-level
classes like Thread and ThreadPool.

The BackgroundWorker
class lets you indicate operation progress, completion, and
cancellation in the Silverlight UI. For example, you can check whether
the background operation is completed or canceled and display a message
to the user.

To use a background worker thread, declare an instance of the BackgroundWorker class at the class level, not within an event handler:

BackgroundWorker bw = new BackgroundWorker();

You can specify whether you want to allow cancellation and progress reporting by setting one or both of the WorkerSupportsCancellation and WorkerReportsProgress properties on the BackgroundWorker object to true. The next step is to create an event handler for the BackgroundWorker.DoWork event. This is where you put the code for the time-consuming operation. Within the DoWork event, call the ReportProgress method to pass a percentage complete value that is between 0 and 100, which raises the ProgressChanged event on the BackgroundWorker object. The UI thread code can subscribe to the event and update the UI based on the progress. If you call the ReportProgress method when WorkerReportsProgress is set to false, an exception will occur.

Check the CancellationPending property of the BackgroundWorker object to determine if there is a pending request to cancel the background operation within the worker_DoWork member function. If CancellationPending is true, set BackgroundWorker.Cancel to true, and stop the operation. To pass data back to the calling process upon completion, set the Result property of the DoWorkerEventArgs object that is passed into the event handler to the object or collection containing the data. The DoWorkerEventArgs.Result is of type object and can therefore be assigned any object or collection of objects. The value of the Result property can be read when the RunWorkerCompleted event is raised upon completion of the operation.

The BackgroundWorker
class tries to prevent deadlocks or cross-thread invocations that could
be unsafe. There are some calls that are always assumed to be called on
the UI thread, such as calling into the HTML Document Object Model
(DOM) or a JavaScript function, so you are not allowed to call them
from a BackgroundWorker class.

A deadlock occurs when two
threads each hold on to a resource while requesting the resource that
the other thread is holding. A deadlock will cause the browser to hang.
It is easy to create a deadlock with two threads accessing the same
resources in an application. Silverlight includes locking primitives,
such as Montior or lock, as well as the ManualResetEvent class.

Exceptions must be
caught within the background thread, because they will not be caught by
the unhandled exception handler at the application level. If an
exception occurs on the background thread, one option is to catch the
exception and set Result to null as a signal that there was an error. Another option is to set a particular value to Result as a signal that a failure occurred.

2.8.4. The Code

In the sample code, you start with the code from Recipe 3,
which includes a form that saves and loads data from isolated storage.
You will save and load data from isolated storage while the background
worker thread is executing to prove that the UI is not locked up by the
long-running operation. You'll modify the UI to include a button to
start the long-running operation as well as a bit of UI work to show
what is going on. Figure 1 shows the UI.

To help keep things clean, the code that was copied from Recipe 2-3 is located in #region
blocks so that it is not a distraction. There is a bit more code in
this recipe, so let's walk through the major code sections. First, you
declare a BackGroundWorker object named worker and initialize it in the constructor Page() for the Page class:

You configure the BackgroundWorker to support cancellation and progress reporting so that you can provide a simple UI to give status. Next, you wire up the DoWork, ProgressChanged, and RunWorkerCompleted events to handlers.

The DoWork event contains the code that the BackgroundWorker thread executes. This is where the long-running operation goes. ProgressChanged and RunWorkerCompleted are events where the UI thread can update status in the UI while the background work is safely executing.

In your DoWork event, you first check to see if there is a cancel request pending and break out of the loop if there is. Otherwise, you call Thread.Sleep to delay execution and ReportProgress
to provide an updated percentage complete. The results of the
background worker thread's effort are passed back to the main thread as
the value of e.Result:

In your case, you simply pass
back a string, but in a scenario with real background work, this could
be a collection of data or objects received over the network. It is not
safe to update the UI from DoWork, so that is why you must pass back results via the events.

To get the work started from the UI, you have a Kick Off Work button that has an event handler with the name DoWorkButton_Click. The code checks to see if the worker is already busy. If not, you set the status by adding text to the WorkResultsTextData TextBox to indicate that work has started, and you call worker.RunWorkerAsync to kick off the work.

To display a dynamic status in the UI, you have a simple ellipse with a Storyboard named AnimateStatusEllipse.
In the button event handler, you call Begin on this object and set it
to run continuously. The animation changes the color from green to
yellow and then back to green, over and over, to indicate that work is
in progress.

In the worker_ProgressChanged event handler, the UI thread receives the latest status from the background worker, available in the e.ProgressPercentage value. It is safe to update the UI in this method, so you set the tooltip on the status ellipse with the latest value.

The worker_RunWorkerCompleted
event fires when the work successfully completes as well as when the
background worker is cancelled by the UI thread, so you first check to
see if e.Cancelled is not true.
If the work successfully completes, you set the ellipse to green,
update the tooltip to indicate that it is complete, and take the value
passed in as e.Result and add it to the TextBox.Text value.

When the user clicks the
ellipse, a dialog is displayed with two buttons so that the user can
click Yes to cancel or decide not to cancel, as shown in Figure 2.

Figure 2. The cancel operation dialog, where the user makes the choice.

The StatusEllipse_MouseLeftButtonDown event checks to see if the background worker thread is actually running and then sets PromptCancelCanvas.Visibility to Visibility.Visible.
That displays the dialog that simply consists of a large rectangle with
a transparent look and a rounded white rectangle with the two buttons.
Clicking Yes fires the ButtonConfirmCancelYes_Click event handler that calls the worker.CancelAsync method.

That completes the walkthrough of the code. Most of the other UI code is generated using Expression Blend. We recommend playing with the UI a bit to understand what it does and then reviewing the corresponding code. Listings 2-13 and 2-14 list the code for this recipe's test application. We don't show the keyframe animation in the AnimateStatusEllipse to make Listing 2-14 easier to navigate.