为什么要使用ConcurrentDictionary?
可用于判断是否已存在同样的键
使用Dictionary添加相同的键时,运行代码的时候会报错,为了避免在运行中出错,可以选用ConcurrentDictionary来进行判断
1.添加元素
ConcurrentDictionary<string, int> dict = new ConcurrentDictionary<string, int>(); dict.TryAdd("key1", 1); dict.TryAdd("key2", 2);
注意:
如果字典中当前不存在该键,则此方法将添加指定的键/值对。 方法返回 true
或false
,具体取决于是否添加新对。2.获取元素
int value1; bool isKey1Exist = dict.TryGetValue("key1", out value1);
3.移除元素
int removedValue; bool isRemoved = dict.TryRemove("key1", out removedValue);
4.更新元素
dict["key1"] = 3;
C# 基础 Dictionary(字典)和ConcurrentDictionary(线程安全的字典)_c# 线程安全字典-CSDN博客
ConcurrentDictionary<TKey,TValue> 类 (System.Collections.Concurrent) | Microsoft Learn
以上两个地址可以更好的辅助了解ConcurrentDictionary