螺纹.NET安全的集合 [英] Thread safe collections in .NET

查看:210
本文介绍了螺纹.NET安全的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是时下当需要一个线程安全的集合(如设置)的标准。 我是否同步它自己,或者是有一个固有的线程安全的集合?

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框架引入了<一个几个线程安全的集合href="http://msdn.microsoft.com/en-us/library/system.collections.concurrent.aspx">System.Collections.Concurrent命名空间:

The .NET 4.0 Framework introduces several thread-safe collections in the System.Collections.Concurrent Namespace:

ConcurrentBag&LT; T>
  &NBSP; &NBSP; &NBSP;再presents对象的线程安全的,无序的集合。

ConcurrentBag<T>
      Represents a thread-safe, unordered collection of objects.

ConcurrentDictionary&LT; TKEY的,TValue>中
  &NBSP; &NBSP;再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安全的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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