.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();
相关推荐
Hello.Reader4 小时前
Flink ZooKeeper HA 实战原理、必配项、Kerberos、安全与稳定性调优
安全·zookeeper·flink
智驱力人工智能5 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
数据与后端架构提升之路6 小时前
论系统安全架构设计及其应用(基于AI大模型项目)
人工智能·安全·系统安全
市场部需要一个软件开发岗位7 小时前
JAVA开发常见安全问题:Cookie 中明文存储用户名、密码
android·java·安全
lingggggaaaa7 小时前
安全工具篇&动态绕过&DumpLsass凭据&Certutil下载&变异替换&打乱源头特征
学习·安全·web安全·免杀对抗
凯子坚持 c7 小时前
CANN-LLM:基于昇腾 CANN 的高性能、全功能 LLM 推理引擎
人工智能·安全
QT.qtqtqtqtqt8 小时前
未授权访问漏洞
网络·安全·web安全
ba_pi11 小时前
每天写点什么2026-02-04(2.1)信息安全
安全·web安全
枷锁—sha11 小时前
Burp Suite 抓包全流程与 Xray 联动自动挖洞指南
网络·安全·网络安全
菩提小狗12 小时前
小迪安全2023-2024|第5天:基础入门-反弹SHELL&不回显带外&正反向连接&防火墙出入站&文件下载_笔记|web安全|渗透测试|
笔记·安全·web安全