问题描述
什么是时下当需要一个线程安全的集合(如设置)的标准。我是否同步它自己,或者是有一个固有的线程安全的集合?
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?
推荐答案
在.NET 4.0框架引入了System.Collections.Concurrent命名空间:
The .NET 4.0 Framework introduces several thread-safe collections in the System.Collections.Concurrent Namespace:
ConcurrentBag< T>
     再presents对象的线程安全的,无序的集合。
ConcurrentDictionary< TKEY的,TValue>中
   再presents可以由多个线程同时访问的键值对的线程安全集合。
ConcurrentDictionary<TKey, TValue>
Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.
ConcurrentQueue&LT; T>
&NBSP; &NBSP;再presents线程安全第一入先出(FIFO)集合。
ConcurrentQueue<T>
Represents a thread-safe first in-first out (FIFO) collection.
ConcurrentStack&LT; T>
&NBSP; &NBSP;再presents线程安全的后进先出(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安全的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!