In Silverlight, there is a BackgroundWorker class that provides a mechanism to perform time consuming tasks on a background thread.

The BackgroundWorker also allows you to report progress back to the UI thread and also cancel the on going operation.

Follow theses simple steps to get the BackgroundWorker started.

Steps

1. Create an instance of the BackgroundWorker class

BackgroundWorker bw = new BackgroundWorker();

Specify whether you want the background operation to allow cancellation and to report progress.

bw.WorkerSupportsCancellation = true;
bw.WorkerReportsProgress = true;

2. Specify the event handlers for the three events DoWorkProgressChanged and RunWorkerCompleted.

bw.DoWork +=
    new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged +=
    new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted +=
    new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

The DoWork handler can perform any time consuming task as desired. You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the ProgressChanged and RunWorkerCompleted events.

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    for (int i = 1; (i <= 10); i++)
    {
        if ((worker.CancellationPending == true))
        {
            e.Cancel = true;
            break;
        }
        else
        {
            // Perform a time consuming operation and report progress.
            System.Threading.Thread.Sleep(500);
            worker.ReportProgress((i * 10));
        }
    }
}

The ProgressChanged and RunWorkerCompleted are handlers in which you can update the UI depending on the data that is provided in the event args

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    this.tbProgress.Text = (e.ProgressPercentage.ToString() + "%");
}

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if ((e.Cancelled == true))
    {
        this.tbProgress.Text = "Canceled!";
    }

    else if (!(e.Error == null))
    {
        this.tbProgress.Text = ("Error: " + e.Error.Message);
    }    else
    {
        this.tbProgress.Text = "Done!";
    }
}

3. Start running the background operation by calling the RunWorkerAsync method.

bw.RunWorkerAsync();

The BackgroundWorker is also available in .NET Framework 4 and is similar to the Silverlight version.

Related Links

Advertisements

Share your thoughts

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s