From my early introduction to WPF I remember having read that WPF binding system takes care of thread marshalling and there is no care required while updating a control value through a view model binding.
Have been working on server side lately and didn't got to spend enough time understanding/validating the above assertion. Like all good IT answers, the above one also has "..it depends" attached to it. And again, like most technology stuff, you get to learn "dependencies" only when you get your hands dirty.
In my latest project I am responsible for a developing a performant WPF UI with real-time updates. Not to mention the efforts I had to take to get real hang of WPF (having read WPF Unleashed 3year back did help, but not in all scenarios).
Recently, I got into a issue where UI would take 30secs at startup. And it made me shine the weapons again....
Facts:
WPF Binding system does take care of marshalling control update operation to UI thread. How?
DispatcherObject is the parent class of all WPF controls. For dependency properties of a control (when binded to a property in viewmodel), all the updates are done by using Dispatcher.BeginInvoke(action). When a property notfication event is raised in viewmodel, it is handled by the control. The control call then marshals message to UI thread to call get on the property that has been modified.
The best way to understand this would be to put a breakpoint into a binded property of viewmodel. Check the Thread.CurrentThread while in the get breakpoint. This thread would be a UI thread (and not a background thread, event if setter was called on a non-UI thread. Which means all viewmodel properties could be set on any thread (not thread agnostic!!) and the update will get marshalled to the control (even though the control is UI thread agnostic).
Where is "it depends"?
This model will not work if you have ObservableCollection/CollectionViewSource in viewmodel!
There are many queries/concerns over this issue. One of the post from
StackOverFlow.
In this scenario we need to be careful about the thread that created ObservbleCollection and the thread that's adding an item in this collection (thread affinity). So, in MVVM all updates to binded properties are not safe.
Also note, since it may not be possible to do everything inside viewmodel on UI thread (eg: getting items from database, or a slow operation). An observablecollection would also demand for locking! An enumerable (ObservableCollection) can not be enumerated and modified parallely. This would need to be controlled using a lock.
Why could this be of concern? And what about UI freeze at startup?
Going one step further. How "best" to marshal a message to UI thread from viewmodel. We have following options:
Application.Current.Dispatcher.Invoke() -- Synchronous, and is a message send (not post).
Application.Current.Dispatcher.BeginInvoke() -- Asynchronous.
Options one is what we were using in our application. Which is what was causing the delay. Because while UI thread was calling InitializeComponent of a control, a set of subscriptions (marshalled to UI thread) using Invoke were causing delay. In my case, the solution was to call BeginInvoke().
Well, not exactly. Again coming to the scenario of ObservableCollection, calling myCollection.Add(item) on UI thread with BeginInvoke is not safe!
Why? Because, it won't be safe to add an item to a collection that could be enumerated by other threads!! There could be a scenario where UI thread is adding an item into this collection, and other background thread is trying to enumerate (you might get lucky here if this collection is only used by some view using binding, and is not enumerated anywhere else. But the point is, it's won't be thread safe).
The other option to get a synschronous operation done using BeginInvoke (post message) is to call BeginInvoke and look through while dispatcher did not complete. Better yet, make use of DispatcherPriority overload and set it to low priority (say Background).
Code:
DispatcherOperation result = Application.Current.Dispatcher.BeginInvoke(action, DispatcherPriority.Background);
while ( result != DispatcherOperationStatus.Completed){
Thread.Sleep(1000); //sleep for 1 sec.
}
In my case, this turned out to be the solution. And I think should be used for the only case (ObservableCollection) where you need to worry about thread in a viewmodel!!
Hope you find it useful!!