in a Windows Phone application, sometimes you might have a long operation , and you do not want to freeze the User Interface (i.e. block the UI thread).

One way to avoid blocking the UI is to use a background worker thread to run the Operation asynchronously and tell it what method to call when it completes processing.

The pseudocode for it…

Start with declaring a background worker.
Tell it what do when finished.

Tell it what method to invoke (which is the long task).
Pass in the argument if any (as an object), so you can have a simple string or a custom object that holds a set of params.

Here is the code for it:

            BackgroundWorker bw = new BackgroundWorker();
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DoneWork); 
            bw.DoWork += new DoWorkEventHandler(DoWork); 
            bw.RunWorkerAsync(arg1);

Note: This concept is applicable to Silverlight in general, and if you are using .NET 4.0 (and not only the Phone), you can use a generic Tuple object for the argument and then type-cast your argument to whatever you passed in.

The signatures for DoWork and DoneWork have to be of the required delegate type, for e.g.:

private void DoWork(object sender, DoWorkEventArgs e)

private void DoneWork(object sender, RunWorkerCompletedEventArgs e)

e.Argument will give you the argument arg1, which you had passed in.

You can store objects you want to send back to the caller as e.Result.

Use this technique to show a progress bar or a wait state in the UI.

Remember, UI operations like updating a list or it’s bindings while done from either delegate need a context switch and are not directly possible because the UI thread is different from the one we might be running on.

This is a pain to code but unavoidable, and to do this, wrap your calls with an anonymous method and call it like this:

            Deployment.Current.Dispatcher.BeginInvoke(
             () => {
                     ... 
                     this.listBox.ItemsSource = items;
                     this.PageTitle.Text = text;             
                   }

Hope that helps…

Advertisements