tags:

views:

43

answers:

2

Are there any potential issues with updating UI bound properties of the ViewModel from the Backgroundworker? I am trying to update the VM while it is bound to the UI, and potentially users might be typing in.. how does the the synchronization work here (I don't think I can use Lock statements from XAML).

Thanks in advance..

A: 

In my experience with Silverlight, trying to do so will cause an exception anyway.

Basically you need to update the bound properties from the dispatcher thread, just as if you were modifying the UI directly.

In order to allow the ViewModel to do that without knowing about a real Dispatcher, I've found it useful to create an IDispatcher interface, then use a SameThreadDispatcher for tests and a SystemDispatcher (which delegates to the real thing) for production. You then pass the ViewModel the IDispatcher as a dependency.

Jon Skeet
I don't know about Silverlight, but in WPF you *can* update ViewModel properties from a worker thread without problems, but collections have to be modified on the UI thread... (see my answer for details)
Thomas Levesque
+1  A: 

When updating scalar properties, you don't need to worry about doing it on the UI thread. The PropertyChanged event is automatically marshalled to the UI thread.

However, it won't work for collections that implement INotifyCollectionChanged. The CollectionChanged event won't be marshalled to the UI thread, and it will cause an exception. So if you modify a collection that is bound to an ItemsControl, you need to use Dispatcher.Invoke (or another synchronization mechanism) to do it on the UI thread. Another option is to use a specialized collection that takes care of marshalling the event to the correct thread. See this article for an example of such a collection.

Thomas Levesque
I am Using Josh Einstein's (http://stackoverflow.com/questions/2091988/how-do-i-update-an-observablecollection-via-a-worker-thread) AddOnUI for updating collections. But i am mainly concerned about <Model> object property in the MVVM which in turn feeds other properties of the ViewModel.
Bhuvan