WPF数据绑定线程安全 [英] WPF DataBinding Thread Safety

查看:58
本文介绍了WPF数据绑定线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TextBox,它绑定到一个属性,该属性在后台线程中以非常快的速度被修改.WPF线程中的数据绑定安全吗?属性或TextBox中的数据是否会不同步?是否有必要(甚至可能)对参与数据绑定的属性使用同步?

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?

我知道,如果属性所在的类实现INotifyPropertyChanged,则绑定框架会自动将UI更新编组为UI线程.但是,这是否仍使数据不同步?如果我理解正确,那么从一个线程写入并从另一个线程读取的变量应该通过同步...数据绑定是异常吗?

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?

谢谢!

推荐答案

是的,在大多数情况下.绑定对于单个对象是线程安全的(因此对于您的字符串应该是合适的).但是,绑定到集合不是线程安全的 线程-仍然需要手动封送处理.如果您有一个控件绑定到一个集合,则不能在后台线程上更改该集合.

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.

我知道,如果属性所在的类实现INotifyPropertyChanged,则绑定框架会自动将UI更新编组为UI线程.但是,这是否仍不使数据不同步?

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?

这不应该不同步,除非多个线程非常快地将变量写入变量(在这种情况下,它们将全部阻塞,直到它们回到同步状态为止,但是一段时间后,线程将用户界面上的等待").封送处理是同步进行的,因此直到绑定是最新的线程才接收值.这可能会减慢您的处理速度,因为必须先进行UI更新,然后才能继续执行后台线程.

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.

这篇关于WPF数据绑定线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆