.NET 5种线程安全集合

在.NET中,有许多种线程安全的集合类,下面介绍五种我们常用的线程安全集合以及他们的基本用法。

ConcurrentBag

ConcurrentBag 是一个线程安全的无序包。它适用于在多线程环境中频繁添加和移除元素的情况。

cs 复制代码
ConcurrentBag<int> concurrentBag = new ConcurrentBag<int>();
 
// 添加元素
concurrentBag.Add(1);
 
// 尝试添加元素
concurrentBag.TryAdd(2);
 
// 移除元素
int item;
concurrentBag.TryTake(out item);

ConcurrentQueue

ConcurrentQueue 是一个线程安全的无序队列。它适用于在多线程环境中频繁添加元素和移除元素(通常是先进先出方式)的情况。

cs 复制代码
ConcurrentQueue<int> concurrentQueue = new ConcurrentQueue<int>();
 
// 添加元素
concurrentQueue.Enqueue(1);
 
// 尝试添加元素
bool isSuccess = concurrentQueue.TryEnqueue(2);
 
// 移除元素
int item;
bool isRemoved = concurrentQueue.TryDequeue(out item);

ConcurrentStack

ConcurrentStack 是一个线程安全的堆栈。它适用于在多线程环境中频繁添加元素和移除元素(通常是后进先出方式)的情况。

cs 复制代码
ConcurrentStack<int> concurrentStack = new ConcurrentStack<int>();
 
// 添加元素
concurrentStack.Push(1);
 
// 尝试添加元素
bool isSuccess = concurrentStack.TryPush(2);
 
// 移除元素
int item;
bool isRemoved = concurrentStack.TryPop(out item);

ConcurrentDictionary<TKey, TValue>

ConcurrentDictionary<TKey, TValue> 是一个线程安全的字典。它适用于在多线程环境中频繁添加、移除和查找键值对的情况。

cs 复制代码
ConcurrentDictionary<int, string> concurrentDictionary = new ConcurrentDictionary<int, string>();
 
// 添加或更新键值对
concurrentDictionary.AddOrUpdate(1, "One", (key, oldValue) => "NewOne");
 
// 尝试添加或更新键值对
bool isSuccess = concurrentDictionary.TryAdd(2, "Two");
bool isUpdated = concurrentDictionary.TryUpdate(2, "NewTwo", "Two");
 
// 移除键值对
string removedValue;
bool isRemoved = concurrentDictionary.TryRemove(1, out removedValue);
 
// 获取值
string value;
bool isFound = concurrentDictionary.TryGetValue(1, out value);

BlockingCollection

BlockingCollection 是线程安全的集合,提供了可阻塞的添加和移除方法

cs 复制代码
BlockingCollection<int> blockingCollection = new BlockingCollection<int>();
 
// 添加元素,如果集合已满,则阻塞当前线程
blockingCollection.Add(1);
 
// 移除元素,如果集合为空,则阻塞当前线程
int item = blockingCollection.Take();
相关推荐
泯泷17 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
泯泷17 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
hez20102 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
Flynt5 天前
npm v12 来了:allowScripts 默认关闭,我的项目差点跑不起来
安全·npm·node.js
小bo波8 天前
使用Thread子类创建线程 VS 使用Runnable接口创建线程的区别
java·多线程·thread·并发编程·runnable
唐青枫8 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫9 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
Caco_D9 天前
一行代码抓遍全网 20 个热榜!Aneiang.Pa 4.0 发布 — 极简 .NET 爬虫库
爬虫·.net
咕白m6259 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net