开发者

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 h开发者_JAVA百科ow 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...


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


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/


In practice it seems to work as expected and seems to be thread-safe (haven't seen anything odd happen or exceptions as a result of updating on background thread). I believe it invokes on to the UI thread when needed, but I'm not too familiar with the internals.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜