在.NET中线程安全集合 [英] Thread safe collections in .NET
问题描述
当需要线程安全收集时,现在的标准是什么(例如Set)。
我是否自己同步,或者是否有固有的线程安全集合?
What is the standard nowadays when one needs a thread safe collection (e.g. Set). Do I synchronize it myself, or is there an inherently thread safe collection?
推荐答案
System.Collections.Concurrent Namespace中的几个线程安全集合:
ConcurrentBag< T>
表示线程安全,无序的对象集合。
ConcurrentBag<T>
Represents a thread-safe, unordered collection of objects.
ConcurrentDictionary< TKey,TValue>
表示可同时由多个线程访问的键值对的线程安全集合。
ConcurrentDictionary<TKey, TValue>
Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.
ConcurrentQueue< T>
表示线程安全的先入先出(FIFO)集合。
ConcurrentQueue<T>
Represents a thread-safe first in-first out (FIFO) collection.
ConcurrentStack< T>
表示线程安全的后进先出(LIFO)集合。
ConcurrentStack<T>
Represents a thread-safe last in-first out (LIFO) collection.
其他默认情况下,.NET Framework中的集合不是线程安全的,需要为每个操作锁定:
Other collections in the .NET Framework are not thread-safe by default and need to be locked for each operation:
lock (mySet)
{
mySet.Add("Hello World");
}
这篇关于在.NET中线程安全集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!