.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();
相关推荐
雨落秋垣21 小时前
多系统 BBR 加速与网络安全综合方案
安全·web安全
m0_7381207221 小时前
渗透测试——Kioptrix5靶机渗透测试详细教程
网络·python·安全·web安全·ssh
YJlio21 小时前
SDelete 学习笔记(9.9):安全擦除原理、SSD 场景与企业合规实战
笔记·学习·安全
lingggggaaaa21 小时前
免杀对抗——C2远控篇&PowerShell&C#&对抗AV-EDR&停用AMSI接口&阻断ETW跟踪&调用
c语言·开发语言·c++·学习·安全·c#·免杀对抗
量子炒饭大师21 小时前
【一天一个计算机知识】—— 【编程百度】悬空指针
c语言·数据结构·c++·git·安全·github·dubbo
搬砖的工人21 小时前
.NET 9.0 与 Swagger 的集成实践:一步步构建Api文档
.net
ZFJ_张福杰1 天前
【技术深度】【安全】Remote Password Protection:一套密码永不上传的登录协议方案(含盲签 + Pairing + Crypto 模块)
安全·密码学·零信任·hsm·双线性映射·远程密码保护
唐青枫1 天前
C#.NET Record Struct 完全解析:语法、语义与最佳实践
c#·.net
I***26151 天前
MySQL 的mysql_secure_installation安全脚本执行过程介绍
数据库·mysql·安全
jenchoi4131 天前
【2025-11-27】软件供应链安全日报:最新漏洞预警与投毒预警情报汇总
网络·安全·web安全·网络安全·npm