简体   繁体   English

.NET是否具有线程安全的通用类?

[英]Does .NET have thread safe generic classes?

I have implemented my own RingBuffer , but I'm surprised to see that .NET does not have one. 我已经实现了自己的RingBuffer ,但是很惊讶看到.NET没有它。 Or even a simply thread safe queue, list or collection? 甚至是简单的线程安全队列,列表或集合?

Why doesn't .NET contain thread safe classes? .NET为什么不包含线程安全类? Are they planned for the future? 他们对未来有计划吗?

Thread safety of general purpose collection classes is of dubious value - more often than not, you don't really need individual operations on them (such as Add or the indexer) to be thread-safe, but you rather need group of operations to be thread-safe. 通用集合类的线程安全性具有可疑的价值-通常,您确实不需要对它们进行单独的操作(例如Add或indexer)来保证线程安全,但是您需要将一组操作线程安全的。 For example, if one thread inserts new items into the collection, while another accesses items in a loop via indexer, it won't matter if both of those methods on the collection will lock it - the code is still broken. 例如,如果一个线程将新项目插入到集合中,而另一个线程通过索引器在循环中访问项目,则集合上的这两个方法都将其锁定都没关系-代码仍然被破坏。 That said, some old non-generic collection classes in System.Collections , such as Hashtable , are thread-safe. 也就是说, System.Collections一些旧的非通用集合类(例如Hashtable )是线程安全的。

Now thread-safe Queue and Stack classes are actually useful (the limitations of their protocol make them suitable for general concurrent access), so their omission isn't really by design, but more of an oversight (or, more likely, constrained resources). 现在,线程安全的QueueStack类实际上是有用的(它们的协议的局限性使其适合于一般的并发访问),因此它们的遗漏并不是设计使然,而是更多的监督(或更可能是受约束的资源) 。 However, you'll see ConcurrentQueue and ConcurrentStack in .NET 4.0 但是,您将在.NET 4.0中看到ConcurrentQueueConcurrentStack

它们将出现在.NET 4.0中,我相信是System.Threading.Collections命名空间(或者这是我在上次查看的CTP中使用的命名空间)。

The .NET 4.0 Framework introduces several thread-safe collections in the System.Collections.Concurrent Namespace: .NET 4.0框架在System.Collections.Concurrent命名空间中引入了几个线程安全的集合:

ConcurrentBag Represents a thread-safe, unordered collection of objects. ConcurrentBag表示线程安全的无序对象集合。

ConcurrentDictionary Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently. ConcurrentDictionary表示键值对的线程安全集合,可以同时由多个线程访问这些键值对。

ConcurrentQueue Represents a thread-safe first in-first out (FIFO) collection. ConcurrentQueue表示线程安全的先进先出(FIFO)集合。

ConcurrentStack Represents a thread-safe last in-first out (LIFO) collection. ConcurrentStack表示线程安全的后进先出(LIFO)集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM