Sunday, December 19, 2010

Property change notifications for multithreaded Silverlight applications

As I’ve been developing more complex Silverlight business applications, I’ve been increasingly relying on BackgroundWorker to offload complex calculations and operations to the background thread.
Something I didn’t have to worry about in the typical user interface thread-only implementation of my app was which thread change notifications fire on.

Here’s a typical scenario:
You have a CLR property on a data/model object in your app. In a background thread, the property is updated.
As all data and model objects should be, the type implements INotifyPropertyChanged (the data binding system relies on this to know when to update bindings).
The property changed event is fired, and listeners react to the change, including the data binding system.
The data binding system throws an invalid cross thread exception, since all UI operations, including handing off the binding changes, need to happen on the UI thread (but it’s happening on a background thread)

BackgroundThreadWithoutDispatcher_thumb.png

So what you really need to do is funnel those change notifications back to always happen on the user interface thread – that’s what makes the most sense given the data binding requirement.
By using a dispatcher, which can accept a BeginInvoke for that other thread, it will all just work and binding will move along happily:

BackgroundThreadWithDispatcher_thumb.png

Read more: Jeff Wilcox