Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Databinding thread safety?

Well lets say i have an object that i databind to, it implements INotifyPropertyChanged to tell the GUI when a value has changed...

if i trigger this from a different thread than the GUI thread how would wpf behave?

and will it make sure that it gets the value of the property from memory and not the cpu cache?

more or less im asking if wpf does lock() on the object containing the property...

like image 971
Peter Avatar asked Mar 31 '10 13:03

Peter


2 Answers

Value changes fired by INotifyPropertyChanged are automatically marshalled back onto the dispatcher. (http://blog.lab49.com/archives/1166)

Fire this event on any thread you like...


Value changes fired by INotifyCollectionChanged are NOT reliably marshalled onto the dispatcher. (http://csharplive.wordpress.com/2008/09/11/wpf-data-binding-observablecollection-cross-thread-binding-support/)

If you need to update an observable collection from a different thread, follow the advice in this link

like image 88
Rob Fonseca-Ensor Avatar answered Oct 22 '22 11:10

Rob Fonseca-Ensor


In addition to @Rob Fonseca-Ensor's answer, there is some good news for those lucky enough to use WPF4.5:

WPF enables you to access and modify data collections on threads other than the one that created the collection. This enables you to use a background thread to receive data from an external source, such as a database, and display the data on the UI thread. By using another thread to modify the collection, your user interface remains responsive to user interaction. (https://msdn.microsoft.com/en-us/library/bb613588(v=vs.110).aspx#xthread_access)

There's a helpful summary by Jonathan Antoine: http://www.jonathanantoine.com/2011/09/24/wpf-4-5-part-7-accessing-collections-on-non-ui-threads/

like image 36
vines Avatar answered Oct 22 '22 09:10

vines