.NET 中的线程安全集合 [英] Thread safe collections in .NET

查看:31
本文介绍了.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?

推荐答案

.NET 4.0 框架在 System.Collections.Concurrent 命名空间:

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

ConcurrentBag
   表示一个线程安全的、无序的对象集合.

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

ConcurrentDictionary
  表示可以被多个线程并发访问的键值对的线程安全集合.

ConcurrentDictionary<TKey, TValue>
    Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.

ConcurrentQueue
  表示线程安全的先进先出 (FIFO) 集合.

ConcurrentQueue<T>
    Represents a thread-safe first in-first out (FIFO) collection.

ConcurrentStack
  表示一个线程安全的后进先出 (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天全站免登陆