ConcurrentDictionary内部函数的使用说明

时间:2022-10-24 19:35:51

AddOrUpdate(...)函数的使用:

private static ConcurrentDictionary<long, string> condic = new ConcurrentDictionary<long, string>(); 

static void Main(string[] args)
{

long key = 1;
condic.TryAdd(key,
"A");
Console.WriteLine(condic[key]);
string newValue = "sss";
// 这里如果将 oldValue + newValue + cKey 变成只有 newValue 就相当于执行AddOrReplace(当然,ConcurrentDictionary对象目前是没这个函数的)
// newValue对于该lambda表达式而言用到了 闭包 的概念,newValue取的是引用该lambda表达式时的当前值,但是如果有多线程并发修改newValue的话,结果可能不合预期。
condic.AddOrUpdate(key, newValue, (cKey, oldValue) => oldValue + newValue + cKey);
Console.WriteLine(condic[key]);
// 输出Asss1
Console.ReadKey();
}