为什么不类,如的BindingList或的ObservableCollection线程安全的? [英] Why aren't classes like BindingList or ObservableCollection thread-safe?

查看:508
本文介绍了为什么不类,如的BindingList或的ObservableCollection线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一次又一次我发现自己不必编写的BindingList的线程安全的版本和的ObservableCollection,因为,当绑定到用户界面,这些控件不能从多个线程改变。我想要了解的是为什么是这样的话 - 它是一个设计错误或者是这种行为故意

Time and time again I find myself having to write thread-safe versions of BindingList and ObservableCollection because, when bound to UI, these controls cannot be changed from multiple threads. What I'm trying to understand is why this is the case - is it a design fault or is this behavior intentional?

推荐答案

问题是设计一个线程安全集合不是简单的。当然这是很简单的设计可以进行修改的集合/多线程读取,而不会损坏状态。但它更难以设计的集合是可​​用的给定的,它的从多个线程更新。看看下面的code作为例子。

The problem is designing a thread safe collection is not simple. Sure it's simple enough to design a collection which can be modified/read from multiple threads without corrupting state. But it's much more difficult to design a collection that is usable given that it's updated from multiple threads. Take the following code as an example.

if ( myCollection.Count > 0 ) {
  var x = myCollection[0];
}

假设MyCollection的是线程安全的集合,其中的添加和更新保证不损坏状态。这code不是线程安全的,是一个竞争条件。

Assume that myCollection is a thread safe collection where adds and updates are guaranteed not to corrupt state. This code is not thread safe and is a race condition.

为什么呢?即使MyCollection的是安全的,没有保证的改变不会发生两者之间的方法调用来MyCollection的:namedly计数和索引。另一个线程可以进来,并删除这些调用之间的所有元素。

Why? Even though myCollection is safe, there is no guarantee that a change does not occur between the two method calls to myCollection: namedly Count and the indexer. Another thread can come in and remove all elements between these calls.

这类型的问题使得使用这种类型的集合很坦率地说是一场噩梦。你永远不能让一个调用的返回值影响,对收集的后续调用。

This type of problem makes using a collection of this type quite frankly a nightmare. You can't ever let the return value of one call influence a subsequent call on the collection.

修改

我扩大在最近的一篇博客文章的讨论:<一href="http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx">http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx

I expanded this discussion on a recent blog post: http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx

这篇关于为什么不类,如的BindingList或的ObservableCollection线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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