Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing ViewModel properties from separate thread

Tags:

mvvm

wpf

In my wpf application, a time consuming operation in my viewmodel is called using a separate thread. This function, however, accesses several properties in the viewmodel that are bound to objects in the view. I tried accessing them directly and I see no complaints on them being owned by the UI thread. I'm interested in knowing the consequences of using them directly between threads.

like image 735
Aks Avatar asked Dec 15 '11 17:12

Aks


1 Answers

You are free to use your ViewModel from any thread - including reading and writing. The one main exception is dealing with collections - data bound collections must be written to on the user interface thread, as the binding doesn't automatically marshal to the UI thread (like simple bindings do).

However, you still should consider having proper synchronization in place for any writes. Normal thread synchronization issues will occur, as the ViewModel is just another class.

That being said, typically, you'll want to handle synchronization slightly differently than you would in many cases. Locks don't typically work on a ViewModel, as the WPF data binding will not lock the objects. As such, you should normally use Dispatcher.Invoke/BeginInvoke to marshal calls back to the user interface thread as needed when synchronization is required in the ViewModel.

like image 119
Reed Copsey Avatar answered Sep 29 '22 01:09

Reed Copsey