WPF DataBinding Thread Safety

允我心安 提交于 2021-02-04 16:08:39

问题


I have a TextBox that's bound to a property that gets modified at a very rapid rate in a background thread. Is data binding in WPF thread safe? Will the data in the property or the TextBox ever get out of sync? Is it necessary (or even possible) to use synchronization on a property that takes part in data binding?

I understand that, if the class on which the property resides implements INotifyPropertyChanged, the binding framework automatically marshalls the UI update to the UI thread. However, doesn't that still allow the data to get out of sync? If I understand correctly, variables that are written from one thread and read from another should by synchronized... is data binding an exception?

thanks!!


回答1:


Yes, for the most part. Binding is thread safe for single objects (so should be fine for your string). However, binding to a collection is not thread safe - and still requires manually marshaling. If you have a control bound to a collection, you cannot change the collection on a background thread.

I understand that, if the class on which the property resides implements INotifyPropertyChanged, the binding framework automatically marshalls the UI update to the UI thread. However, doesn't that still allow the data to get out of sync?

This shouldn't get out of sync, unless multiple threads are writing to the variable very quickly (in which case, they'll all block until they get back in sync, but there is a period of time where threads will "wait" on the UI). The marshaling happens synchronously, so the thread doesn't receive values until the binding is up to date. This can slow down your processing, as the UI update has to happen before your background thread can continue.




回答2:


Yes, it is usually thread safe. In WPF (unlike WinForms) the data binding classes look for the UI thread's Dispatcher and use it (if needed) to automatically marshal to the UI thread. Note, however, that this is done synchronously- your background thread will block while the UI is redrawn, and I have seen that cause choppyness, "freezing", and other unintended effects with rapid background updates.

See a similar question here: WPF Databinding thread safety?



来源:https://stackoverflow.com/questions/7342462/wpf-databinding-thread-safety

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!