WPF MVVM Updating UI Properties from BackgroundWorker

Are there any potential problems updating the ViewModel interface properties from the Background Worker? I am trying to update a virtual machine while it is connected to the user interface, and potentially users can enter text. How synchronization works here (I don’t think I can use Lock statements from XAML).

Thanks in advance.

+6
c # wpf mvvm
source share
2 answers

When updating scalar properties, you don’t need to worry about this in the user interface thread. The PropertyChanged event is automatically sorted by UI thread.

However, it will not work for collections that implement INotifyCollectionChanged . The CollectionChanged event will not be bound to the user interface thread, and this will throw an exception. Therefore, if you change the collection bound to ItemsControl , you need to use Dispatcher.Invoke (or another synchronization mechanism) to do this in the user interface thread. Another option is to use a specialized collection that takes care of sorting the event to the correct topic. See this article for an example of such a collection.

+3
source share

In my experience with Silverlight, trying to do this will throw an exception.

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

To let the ViewModel do this without knowing the real Dispatcher , I found it useful to create an IDispatcher interface, then use the SameThreadDispatcher tags for tests and SystemDispatcher (which are the delegates to the real thing) for production. Then you pass the ViewModel IDispatcher as a dependency.

+1
source share

All Articles