Rants and Raves

Thanks for visiting my blog!

Executing Code on the UI Thread in Silverlight 2
Executing Code on the UI Thread in Silverlight 2
May 6, 2008

Url: http://wilderminds.blob.core.windows.net/downloads/silverlightcros…
Silverlight Logo
With the asynchronicity question still dogging Silverlight 2, I thought I’d mention an oft forgotten little class in Silverlight (and in WPF) called the Dispatcher. Much of the confusion with asynchronous programming seems to stem from the fact that developers over complicate the problem.  Think that they need to handle the cross thread calls themselves. They tend to create two way communications for this or overuse the BackgroundWorker’s ReportProgress functionality.

The key to simplifying calling the UI thread is the Dispatcher class.  This class supports a static (or shared) interface for executing code on the UI thread.  For example, you can call Dispatcher.BeginInvoke to invoke some arbitrary code on the UI thread:

// With Simple Lambda
Dispatcher.BeginInvoke(() => DoSomething());

// Also With Lambda
Dispatcher.BeginInvoke(() =>
  {
    DoSomething();
  }
  );

// or with Anonymous Delegate
Dispatcher.BeginInvoke(delegate()
  {
    DoSomething();
  } );

This is all is required to execute code on the UI thread.  The Dispatcher guarantees that this code is executed on the main UI thread. This is simplified versus the same WPF code. The Windows Presentation Foundation  uses a a prioritized message queue so that the Dispatcher really allows developers to not only make calls to the UI thread, but do so with some priority attached.  (See my MSDN article on the Dispatcher in WPF for a more detailed explanation). In Silverlight 2, the model is simplified (for better or worse). When calling the UI thread, you simply need to specify the code to call on the UI thread…the priority is gone.

Unfortunately there is no way currently to reliably test for the UI thread (again unlike in WPF where the DispatcherObject was part of the object hierarchy so you could call CheckAccess to see if you were on the UI thread). Because of this Silverlight 2 has a fundamental problem. It is unclear when we are on the UI thread. This is especially problematic for the event driven architecture that Silverlight 2 employs. This is exemplified by the fact that during some events (WebClient calls are especially prone to this behavior) seem to fail silently when you try and update the UI.  This is unlike the BackgroundWorker who throws an UnauthorizedAccessException (with the message of Invalid Cross Thread Access). So at times I find myself throwing in Dispatcher.BeginInvoke calls if the UI is failing to update in events (both control events and other events). This isn’t a great solution but it does solve the issue much of the time.

I’ve attached a simple Silverlight 2 sample that shows this technique.  Let me know if you have any questions about this sample.