Updating the UI Thread in SL2

18 04 2008

Just as in WPF, Silverlight only allows you to update the UI from a UI Thread. This is done trough the Dispatcher object. There are a lot of samples floating around but none did exactly what I was looking for.

Let’s say we have the following code:

// Create a new thread and Start it

new Thread(new ThreadStart(() =>

{

    // Do some NON UI Asynchronous work here       

    PopulateSomeDataFromOtherData();

 

    // THIS WILL NOT WORK

    UpdateUI();

}

The code starts a new thread, then does some work on the thread. And when it’s finishes it tries to update the UI, this will fail!

To make this work, we need to tell the UI thread to execute this code trough the Dispatcher object:

First you define a custom (empty) delegate:

public delegate void UpdateUIDelegate();

And then you change the erroneous previous code to:

// Create a new thread and Start it

new Thread(new ThreadStart(() =>

{

    // Do some NON UI Asynchronous work here       

    PopulateSomeDataFromOtherData();

 

    // Define an action to execute in the UI Thread

    UpdateUIDelegate action = new UpdateUIDelegate(() =>

    {

        //Update the UI

        UpdateUI();

    });

 

    // Tell the UI Thread (Dispatcher) to execute the action

    Application.Current.RootVisual.Dispatcher.BeginInvoke(action);

})

).Start();

The changes use the Dispatcher from the RootVisual to execute the action delegate. This will nicely update the UI from a non UI-Thread.

NOTE: The Dispatcher object used in this sample is from the RootVisual. But every Control has it’s own Dispatcher object. Use it when it’s available, it will save you a lot of debugging.

For some more info on Silverlight and Threading check:

Stay in the light!

Robertjan Tuit

 


Actions

Informations

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>