C# 浅谈线程安全的字典集合ConcurrentDictionary

avatar
作者
筋斗云
阅读量:6

ConcurrentDictionary 是 C# 中的一个线程安全的字典集合 TryAdd(TKey key, TValue value): 尝试添加一个键值对到字典中,如果键已存在,则不执行任何操作并返回 false;如果添加成功,则返回 true。 TryGetValue(TKey key, out TValue value): 尝试获取与给定键相关联的值,如果键存在于字典中,则将该值赋给 value 参数并返回 true;如果键不存在,则 value 参数保持不变并返回 false。 TryRemove(TKey key, out TValue value): 尝试从字典中移除具有指定键的键值对,如果移除成功,则将移除的值赋给 value 参数并返回 true;如果键不存在,则 value 参数保持不变并返回 false。

ConcurrentDictionary dict = new ConcurrentDictionary(); 

// 启动多个任务来向字典中添加数据 Parallel.For(1, 1000, i => {     dict.TryAdd(i, $"Value {i}"); });
// 尝试获取并输出字典中的值 if (dict.TryGetValue(500, out string value)) {     Console.WriteLine($"Value for key 500: {value}"); } else {     Console.WriteLine("Key 500 does not exist in the dictionary."); }
// 尝试移除并输出字典中的值 if (dict.TryRemove(500, out value)) {     Console.WriteLine($"Removed value for key 500: {value}"); } else {     Console.WriteLine("Key 500 does not exist in the dictionary."); }

 

 

 

 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!