Dispatcher and Multi-threading in Silverlight 3

In Silverlight 3, as with WinForms and WPF,  we need to be careful about cross thread communication. Controls instantiated in the XAML DOM belong to the UI thread and only the UI thread can update them. To see this, try updating the UI from a different thread,

public MainPage() {
    InitializeComponent();
 
    // Explicitly start a new thread,
    Thread myThread = new Thread(FillRectangle);
    myThread.Start();
}
 
void FillRectangle() {
    // Try to update the UI thread...
    MyRectangle.Fill = new SolidColorBrush(Colors.Red);
}
 

You’ll see an error like this,

Capture

To alleviate this Silverlight gives us two constructs,

1. The Dispatcher class: This class guarantees  that the code will be executed on the UI thread.

public MainPage() {
    InitializeComponent();
 
    // Explicitly start a new thread
    Thread myThread = new Thread(FillRectangle);
    myThread.Start();
}
 
void FillRectangle() {
    // Can't update the UI thread directly
    //MyRectangle.Fill = new SolidColorBrush(Colors.Red);

    // But perfectly safe to update the UI using the Dispatcher
    Dispatcher.BeginInvoke(() => MyRectangle.Fill = new SolidColorBrush(Colors.Red));
}
 

2. The BackgroundWorker class: Using this class gives you a new thread but also gives you a way to update the UI in a safe way.

public MainPage() {
    InitializeComponent();
    BackgroundWorker bg = new BackgroundWorker();

    // This method is called on the background thread
    bg.DoWork += CrossThreadUnsafe;

    // This method is called on the UI thread
    bg.RunWorkerCompleted += CrossThreadSafe;

    // Start the thread
    bg.RunWorkerAsync();
}
 
void CrossThreadUnsafe(object sender, DoWorkEventArgs e) {
    // Don't update the UI here - uncommenting will cause 'Invalid cross-thread access error'
    //MyRectangle.Fill = new SolidColorBrush(Colors.Red);
}
 
void CrossThreadSafe(object sender, RunWorkerCompletedEventArgs e) {
    // Perfectly safe to update the UI from here
    MyRectangle.Fill = new SolidColorBrush(Colors.Red);
}
 

Or if you want, write your own BackgroundWorker class.

Also, Silverlight provides a DispatcherTimer  class which is a UI-thread safe timer (as opposed to the Timer class), for an example see here.

Digg This

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

7 Responses to Dispatcher and Multi-threading in Silverlight 3

  1. FrencefeN says:

    SDVSDV DSVDSVDSVSD

  2. Rodney says:

    Hello,

    Can you please explain a little further – I have copied and pasted your code above into my Silverlight project.
    However, it throws on error on this line :

    Error 1 An object reference is required for the non-static field, method, or property ‘xyz.FillRectangle()’ xyz.xaml.cs 547 50

    any idea why please?

  3. Rodney says:

    A little more information: (I am using SL4):

    If I paste this into my class:
    Dispatcher.BeginInvoke(() => MyRectangle.Fill = new SolidColorBrush(Colors.Red));

    I get this message:
    “Cannot convert lambada expression to type System.Delegate because it is not a delegate type”

    Any tips on what that means please?

  4. BoodoTymn says:

    Bad to appearances, entanglement map does not rely on the consciousness of different programming languages, including HTML and PHP easiest. Trap design is also a serendipitous find in regard to those who pull someone’s leg a sense of artistic and leaning to spawn projects unique. On web pages is not no greater than wyklepanie tranquillity, but also correct layout that will lure internet users to visit. It is tucker if the entire band schemer also has a graphic design studio, then you can be scarcely fixed that the terminal culminate meets our expectations. In principle the choice of such a throng thoroughly check her portfolio, the more it can burnish up in requital for what the train does and what livelihood has done. Of course, taking up the design yourself, and you have to take a everything of knowing in the delineate, but also in creating vector and raster. Although the press into service of software like Photoshop is not complicated, it’s really impregnable to the layman to do something real and trim, what wishes be, in the service of example, gave as the logo.
    Articles obout graphicks

  5. scatpeeD says:

    russian girl fart on slave anal sex without shit streaming scat movies
    … dirty lesbian, lesbian female domination story, hardcore porn dvds, … lesbo rimjob, free scat mpegs, schoolgirls panties, secretary lesbians, … 31 May 2009 … Flurl is a video search engine featuring funny videos, viral videos, and the best videos on the Internet. … naked pics see download free lesbien porn substance dominican ladys gone … fruit asshole sniffing fetish scat enemy red haired milfs locate believe …
    asian puking scat sex free group lesbian

  6. Charlesnini says:

    Карьерный крупнозернистый песок, как правило используется при производстве бетонов и песок бровары доставка изделий из бетона. Такие изделия, как: тротуарная плитка, бордюры и колодезные кольца требуют в своей технологии применения крупнозернистого мытого карьерного песка. Песок бывает разных по крупности зерен: крупный от 2 до 5 мм в диаметре, средний от 0,5 до 2 мм и мелкий от 0,15 до 0,5 мм. Чаще всего используют средний песок.

Leave a reply to scatpeeD Cancel reply