.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();
相关推荐
黄乐荣28 分钟前
系统分析师-2025-11
安全
算法大模型备案干货咪2 小时前
《把内容安全做成CI卡点:AIGC合规的工程化落地》
安全·ci/cd·aigc
赫媒派2 小时前
OpenAI Recurrent Depth:3个安全隐患
安全·openai·ai编程
是隼人3 小时前
buuctf-pwn PWN1题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
恒拓高科WorkPlus3 小时前
企业如何搭建安全内部通讯平台|企业内部通讯平台怎么选才更安全?
jvm·数据库·安全
Lost of 程序猿3 小时前
.NET 线程安全集合与并发数据结构深度实战:从 lock 到无锁
数据结构·安全·.net
梦想很大很大4 小时前
从 Scope State 到 Guardrails:Workrun 如何为 Agent 工作流建立安全边界
安全·agent·workflow
Neighbor_OldY4 小时前
云上证书过期与HTTPS安全治理实战:证书到期没人管、自动化续期与证书链排查
安全·https·自动化
咖啡星人k4 小时前
2026 智能体安全进阶:把注入和越权写进SPEC,MonkeyCode 云端跑通
人工智能·安全·机器学习
迅利科技5 小时前
航空 EWIS 线束数字化,CATIA 如何保障复杂机载电气流体系统安全合规
安全·系统安全