参考网址: https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/

Thread-Safe Collections

  • 03/30/2017
  • 3 minutes to read

The .NET Framework 4 introduces the System.Collections.Concurrent namespace, which includes several collection classes that are both thread-safe and scalable. Multiple threads can safely and efficiently add or remove items from these collections, without requiring additional synchronization in user code. When you write new code, use the concurrent collection classes whenever multiple threads will write to the collection concurrently. If you are only reading from a shared collection, then you can use the classes in the System.Collections.Generic namespace. We recommend that you do not use 1.0 collection classes unless you are required to target the .NET Framework 1.1 or earlier runtime.

Thread Synchronization in the .NET Framework 1.0 and 2.0 Collections

The collections introduced in the .NET Framework 1.0 are found in the System.Collections namespace. These collections, which include the commonly used ArrayList and Hashtable, provide some thread-safety through the Synchronized property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation for large collections. Also, the design is not completely protected from race conditions. For more information, see Synchronization in Generic Collections.

The collection classes introduced in the .NET Framework 2.0 are found in the System.Collections.Generic namespace. These include List<T>Dictionary<TKey,TValue>, and so on. These classes provide improved type safety and performance compared to the .NET Framework 1.0 classes. However, the .NET Framework 2.0 collection classes do not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently.

We recommend the concurrent collections classes in the .NET Framework 4 because they provide not only the type safety of the .NET Framework 2.0 collection classes, but also more efficient and more complete thread safety than the .NET Framework 1.0 collections provide.

Fine-Grained Locking and Lock-Free Mechanisms

Some of the concurrent collection types use lightweight synchronization mechanisms such as SpinLockSpinWaitSemaphoreSlim, and CountdownEvent, which are new in the .NET Framework 4. These synchronization types typically use busy spinning for brief periods before they put the thread into a true Wait state. When wait times are expected to be very short, spinning is far less computationally expensive than waiting, which involves an expensive kernel transition. For collection classes that use spinning, this efficiency means that multiple threads can add and remove items at a very high rate. For more information about spinning vs. blocking, see SpinLock and SpinWait.

The ConcurrentQueue<T> and ConcurrentStack<T> classes do not use locks at all. Instead, they rely on Interlocked operations to achieve thread-safety.

Note

Because the concurrent collections classes support ICollection, they provide implementations for the IsSynchronized and SyncRoot properties, even though these properties are irrelevant. IsSynchronized always returns false and SyncRoot is always null (Nothing in Visual Basic).

The following table lists the collection types in the System.Collections.Concurrent namespace.

FINE-GRAINED LOCKING AND LOCK-FREE MECHANISMS
Type Description
BlockingCollection<T> Provides bounding and blocking functionality for any type that implements IProducerConsumerCollection<T>. For more information, see BlockingCollection Overview.
ConcurrentDictionary<TKey,TValue> Thread-safe implementation of a dictionary of key-value pairs.
ConcurrentQueue<T> Thread-safe implementation of a FIFO (first-in, first-out) queue.
ConcurrentStack<T> Thread-safe implementation of a LIFO (last-in, first-out) stack.
ConcurrentBag<T> Thread-safe implementation of an unordered collection of elements.
IProducerConsumerCollection<T> The interface that a type must implement to be used in a BlockingCollection.

Related Topics

RELATED TOPICS
Title Description
BlockingCollection Overview Describes the functionality provided by the BlockingCollection<T> type.
How to: Add and Remove Items from a ConcurrentDictionary Describes how to add and remove elements from a ConcurrentDictionary<TKey,TValue>
How to: Add and Take Items Individually from a BlockingCollection Describes how to add and retrieve items from a blocking collection without using the read-only enumerator.
How to: Add Bounding and Blocking Functionality to a Collection Describes how to use any collection class as the underlying storage mechanism for an IProducerConsumerCollection<T> collection.
How to: Use ForEach to Remove Items in a BlockingCollection Describes how to use foreach, (For Each in Visual Basic) to remove all items in a blocking collection.
How to: Use Arrays of Blocking Collections in a Pipeline Describes how to use multiple blocking collections at the same time to implement a pipeline.
How to: Create an Object Pool by Using a ConcurrentBag Shows how to use a concurrent bag to improve performance in scenarios where you can reuse objects instead of continually creating new ones.

Reference

System.Collections.Concurrent


Recommended content

  • ConcurrentQueue<T> Class (System.Collections.Concurrent)

    Represents a thread-safe first in-first out (FIFO) collection.

  • ConcurrentBag<T> Class (System.Collections.Concurrent)

    Represents a thread-safe, unordered collection of objects.

  • When to Use a Thread-Safe Collection

    Know when to use a thread-safe collection in .NET. There are 5 collection types that are specially designed to support multithreaded add & remove operations.

  •  

C# 线程安全的集合的更多相关文章

  1. java 中如何声明线程安全的集合 set, map 和list

    线程安全的集合 http://blog.sina.com.cn/s/blog_508938e10102v1ig.html //make thread-safe list List MyStrList ...

  2. java利用线程池处理集合

    java利用线程池处理集合 2018年07月23日 17:21:19 衍夏成歌 阅读数:866   版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/s ...

  3. .NET 同步与异步 之 线程安全的集合 (十一)

    本随笔续接:.NET 同步与异步 之 警惕闭包(十) 无论之前说的锁.原子操作 还是 警惕闭包,都是为安全保驾护航,本篇随笔继续安全方面的主题:线程安全的集合. 先看一下命名空间:System.Col ...

  4. java 中如何声明线程安全的集合 set, map 和list【转】

    线程安全的集合 引用自 http://blog.sina.com.cn/s/blog_508938e10102v1ig.html //make thread-safe list List MyStrL ...

  5. Java中线程安全的集合

    如果多线程并发的访问与一个数据结构,那么很容易破坏一个数据结构. 例如,一个线程可能要向一个散列表中插入一条数据的过程中,被剥夺了控制权.如果另外一个线程也开始遍历同一个链表,很可能造成混乱,抛出异常 ...

  6. Java多线程理解:线程安全的集合对象

    1.概念介绍 线程安全就是多线程访问时,采用了加锁机制,当一个线程访问该类的某个数据时,进行保护,其他线程不能进行访问直到该线程读取完,其他线程才可使用.不会出现数据不一致或者数据污染. 线程不安全就 ...

  7. java 多线程 线程安全及非线程安全的集合对象

    一.概念: 线程安全:就是当多线程访问时,采用了加锁的机制:即当一个线程访问该类的某个数据时,会对这个数据进行保护,其他线程不能对其访问,直到该线程读取完之后,其他线程才可以使用.防止出现数据不一致或 ...

  8. CopyOnWriteArrayList线程安全的集合

    CopyOnWriteArrayList是线程安全的集合.本身就是安全的,同时只能被一个进程所访问. 属于JUC并发编程里面的内容. public static void main(String[] ...

  9. Java——线程安全的集合

    线程安全的集合    java.util.concurrent包:ConcurrentHashMap,ConcurrentSkipListMap,ConcurrentSkipListSet,Concu ...

  10. scala 数据结构(十一):流 Stream、视图 View、线程安全的集合、并行集合

    1 流 Stream stream是一个集合.这个集合,可以用于存放无穷多个元素,但是这无穷个元素并不会一次性生产出来,而是需要用到多大的区间,就会动态的生产,末尾元素遵循lazy规则(即:要使用结果 ...

随机推荐

  1. Kubernetes 1.13.3 部署 Prometheus+Grafana-7.5.2(最新版本踩坑)

    本教程直接在 Kubernetes 1.13.3 版本上安装 Prometheus 和 Grafana-7.5.2,至于它们的原理和概念就不再赘述,这里就直接开始操作. Git 下载相关 YAML 文 ...

  2. nacos集群部署

    对于nacos的集群部署,建议大家参考nacos官网进行,地址:https://nacos.io/zh-cn/docs/cluster-mode-quick-start.html 下面是我自己部署na ...

  3. PO封装设计模式 -- Web页面端测试

    一.已登录页面 -->新建PO封装的包 -- 以下源码适用于python3以上的版本 代码优化新增 Image -->对操作步骤进行截图 二.basepage 包基础类的封装如下: fro ...

  4. C语言变量为何先定义后使用

    C语言中,对变量的使用,首先要先定义.说明其数据类型.原因可能如下: 1不同类型的变量,其编码表示方式可能不同. 2不同类型的变量,其占有的空间大小不同.不事先说明无法在内存中开辟空间.

  5. [Vue warn]: “TypeError: Cannot read property ‘slideTo‘ of undefined“

    问题: 使用Vue插件swiper,报如下bug: 解决: 报错原因: vue-awesome-swiper下载版本问题 解决: 如果写成下面这样报错: 则加上$ 反之,删除$ 问题解决

  6. PAT乙级:1083 是否存在相等的差 (20分)

    PAT乙级:1083 是否存在相等的差 (20分) 题干 给定 N 张卡片,正面分别写上 1.2.--.N,然后全部翻面,洗牌,在背面分别写上 1.2.--.N.将每张牌的正反两面数字相减(大减小), ...

  7. Linux + .net core 开发升讯威在线客服系统:首个经过实际验证的高性能版本

    业余时间用 .net core 写了一个在线客服系统.并在博客园写了一个系列的文章,写介绍这个开发过程: .net core 和 WPF 开发升讯威在线客服系统:目录 https://blog.she ...

  8. yaml 文件解析

    前言 yaml文件其实也是一种配置文件类型,相比较ini,conf配置文件来说,更加的简洁,操作也更加简单,同时可以存放不同类型的数据,不会改变原有数据类型,所有的数据类型在读取时都会原样输出,yam ...

  9. 基于小熊派Hi3861鸿蒙开发的IoT物联网学习【一】

    基于小熊派鸿蒙季BearPi-HM_Nano HarmonyOS 鸿蒙系统Hi3861开发板NFC  开发步骤:1.购买开发板:某宝上购买就行 2.安装开发环境 3.下载源码 4.编写案例并执行 开发 ...

  10. VM12升级VM15

    之前一直用的12,现在想要升级为15.主要是为了解决kali操作系统版本兼容问题 打开VM12,点击[帮助]-->[软件更新]--> [检查更新] 发现有VM15,点击[了解详情] VM1 ...