线程安全,列表,绑定和WPF [英] Thread safety, lists, binding and WPF

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

问题描述

我有一个绑定到一个集合的WPF的ListView(列表< T> )。这是目前从当前线程它工作正常更新。

I have a WPF ListView that is bound to a collection (List<T>). It is currently updated from the current thread which works ok.

我想移动的逻辑更新列表到一个线程,我看到有关线程安全和一些潜在的问题列表的约束力。我大可放心,除非我叫绑定,将不会更新 NotifyPropertyChanged ?为 NotifyPropertyChanged 阻塞调用还是只是将它添加到消息队列;在这种情况下肯定有可能是这样一种情况:我告诉的ListView 收集更新,但由当时的绑定更新我可能会在其他线程将被修改集合抛出一个异常,或程序崩溃。

I want to move the logic for updating the list into a thread and I see some potential issues regarding thread safety and the binding of the list. Can I be assured that the binding will not be updated unless I call NotifyPropertyChanged? Is NotifyPropertyChanged a blocking call or does it just add it to a message queue; in this instance surely there may be a condition where I tell the ListView the collection updated, but by the time the binding updates I may be modifying the collection in the other thread which will throw an exception or crash the program.

什么是在这样的情况下实现线程安全的最佳方法是什么?

What is the best method for implementing thread safety in such a scenario?

推荐答案

INotifyPropertyChanged的不是线程安全的,它也阻止调用线程。

INotifyPropertyChanged is not thread safe, and it does block the calling thread.

最好?这是一个很好的问题。我不知道。底线是,在一段时间或其他,呼叫必须被编组到UI线程。当你这样做吗?

Best? That's A good question. I dunno. The bottom line is that, at some time or another, calls must be marshalled onto the UI thread. When do you do this?

您可以1)做好一切准备,然后将其传递到UI线程当UI,然后更新。或者,你可以2)实现INotifyPropertyChanged,使该事件的触发总是发生在UI线程上,或3),你可以做很多不同的事情之一。

You could 1) prepare everything, then deliver it to the UI thread where the UI is then updated. Or, you could 2) implement INotifyPropertyChanged and make the firing of that event always happen on the UI thread, or 3) you could do one of a number of different things.

然而,通常你想更新到用户界面(而不是一次一个,因为你会加入一个项目时一个ObservableCollection,例如获得)发生的一次。所以它可能是最好使实现INotifyProperty和CollectionChanged并使用这些有些线程安全的基类。

Usually, however, you would want updates to the UI to happen all at once (not one at a time, as you would get when adding single items to an ObservableCollection, for instance). So it might be advisable to make some thread safe base classes that implement INotifyProperty and CollectionChanged and use these.

有什么的框架,为你做这个,很遗憾。

There is nothing in the framework that will do this for you, unfortunately.

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

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