SynchronizedCollection<T> 和 SynchronizedCollection<T> 有什么区别?和其他并发集合? [英] What is the difference between SynchronizedCollection<T> and the other concurrent collections?

查看:31
本文介绍了SynchronizedCollection<T> 和 SynchronizedCollection<T> 有什么区别?和其他并发集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SynchronizedCollectionSystem.Collections.Concurrent 命名空间中的并发集合有何不同,除了 Concurrent Collections 作为命名空间和 >SynchronizedCollection 是一个类吗?

How does SynchronizedCollection<T> and the concurrent collections in the System.Collections.Concurrent namespace differ from each other, apart from Concurrent Collections being a namespace and SynchronizedCollection<T> being a class?

SynchronizedCollection 和并发集合中的所有类都提供线程安全集合.我如何决定何时使用一种而不是另一种,为什么?

SynchronizedCollection<T> and all of the classes in Concurrent Collections provide thread-safe collections. How do I decide when to use one over the other, and why?

推荐答案

SynchronizedCollection首先在 .NET 2.0 中引入,以提供线程安全的集合类.它通过锁定来实现这一点,因此您基本上拥有一个 List,其中每个访问都包含在一个 lock 语句中.

The SynchronizedCollection<T> class was introduced first in .NET 2.0 to provide a thread-safe collection class. It does this via locking so that you essentially have a List<T> where every access is wrapped in a lock statement.

System.Collections.Concurrent 命名空间要新得多.它直到 .NET 4.0 才被引入,它包含了大量改进和更加多样化的选择.这些类不再使用锁来提供线程安全,这意味着在多个线程同时访问其数据的情况下,它们应该可以更好地扩展.但是,在这些选项中明显没有实现 IList 接口的类.

The System.Collections.Concurrent namespace is much newer. It wasn't introduced until .NET 4.0 and it includes a substantially improved and more diverse set of choices. These classes no longer use locks to provide thread safety, which means they should scale better in a situation where multiple threads are accessing their data simultaneously. However, a class implementing the IList<T> interface is notably absent among these options.

因此,如果您的目标是 .NET Framework 4.0 版,则应尽可能使用 System.Collections.Concurrent 命名空间提供的集合之一.就像在 System.Collections.Generic 命名空间,您需要选择其功能和特性最适合您的特定需求的命名空间.

So, if you're targeting version 4.0 of the .NET Framework, you should use one of the collections provided by the System.Collections.Concurrent namespace whenever possible. Just as with choosing between the various types of collections provided in the System.Collections.Generic namespace, you'll need to choose the one whose features and characteristics best fit your specific needs.

如果您的目标是旧版本的 .NET Framework 或需要一个实现 IList 接口的集合类,则必须选择 SynchronizedCollection<;T> 类.

If you're targeting an older version of the .NET Framework or need a collection class that implements the IList<T> interface, you'll have to opt for the SynchronizedCollection<T> class.

MSDN 上的这篇文章也值得一读:何时使用线程-安全收藏

This article on MSDN is also worth a read: When to Use a Thread-Safe Collection

这篇关于SynchronizedCollection&lt;T&gt; 和 SynchronizedCollection&lt;T&gt; 有什么区别?和其他并发集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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