
Thread Safety in a (Property)Changing World
March 8, 2009
I’m really loving the power and simplicity of MVVM (Model View View-Model). The View-Model communicates changes to the binding system via the ‘PropertyChanged‘ event of INotifyPropertyChanged. I also like to communicate changes from the Model to the View-Model via this event.
But there is a potential rub here. Whenever you do some work on a background thread, you need to make sure you pass execution back to the UI thread if the resulting activity ends up changing the UI (a foregone conclusion really when firing PropertyChanged). It’s a real drag having to invoke the Dispather whereever you know (or suspect) firing the event will cause a threading exception because an attempt is made to update the UI on a background thread.
Well, after poking through Nikhil’s excellent framework/sample – I found a great way to remove this drag from my life (and your life) forever! Below is a base class you can use to derive model’s and view-models on that will always fire the PropertyChanged event over on the UI thread. Dispatcher arbitrage is now a gone-burger.

And for good measure, here’s an asynchronous unit test that verifies this behavior:

Hey Phil,
Can you only use that Asynchronous attribute for unit testing Silverlight? I know it is part of the framework but it seems to me that that could apply to all kinds of situations. I’ve used Microsoft’s Chess framework but that can be very trying to work with.
Adam
G’day Adam,
You’re right, this is totally useful in other areas, and I’m yet to find a decent way of doing this with the native testing frameworks (NUnit or the VisualStudio tools).
Jeff Wilcox did a really good job building this – and it’s kind of amazing that something this useful isn’t baked into the CLR version of things.
If you find anything, do let me know. The closest I’ve come is mucking around with the objects in the Thread namespace – but it’s painful.
I assume that this only works if the ViewModel or Model is created on the UI thread. That is probably a valid assumption for a ViewModel, but possibly not for a Model (eg. creating instances of a Model on a background thread in response to callbacks from a long-running service call).
Yes – you are right James. This is more appropriate for a ViewModel scenario.