1,定义
ConcurrentDictionary<TKey,TValue>是一个可由多个线程同时访问的键/值对的线程安全集合。
2,参数的类型
TKey:字典中键的类型。
TValue:字典中值的类型。
3,常用的方法
TryAdd:尝试添加一个键值对,添加成功返回 true,添加失败返回false。
ConcurrentDictionary<int ,string>student=new ConcurrentDictionary<int ,string>();
student.TryAdd(1,"Tom");
student.TryAdd(2,"aa");
AddOrUpdate: 尝试修改一个值,修改成功返回true,修改失败返回false。
//修改值,如果没有这个键就添加,返回添加键的值,返回bb
string res1 = student.AddOrUpdate(3, "bb",(x,y)=>"cc");
//有这个键,直接修改,返回修改后的,即dd
string res2 = student.AddOrUpdate(2, "11", (x, y) => "dd");
ToArray:用于将字典的内容复制到一个新的数组中
var array = student.ToArray();
以上三个方法都是线程安全的,在多个线程都需要对字典进行读写等操作时,使用ConcurrentDictionary可以确保线程安全。