ConcurrentDictionary GetOrAdd方法不是線程安全的
兩個add方法委托都執(zhí)行了侦副。
最后有可能是Hello from t1 或者Hello from t2疏叨。
Thread t1 = new Thread(() =>
{
store.GetOrAdd(0, i =>
{
string msg = "Hello from t1";
Trace.WriteLine(msg);
Thread.SpinWait(10000);
return msg;
});
});
Thread t2 = new Thread(() =>
{
store.GetOrAdd(0, i =>
{
string msg = "Hello from t2";
Trace.WriteLine(msg);
Thread.SpinWait(10000);
return msg;
});
});
t1.Start();
t2.Start();
t1.Join();
t2.Join();
foreach (var item in store.Values)
{
Console.WriteLine(item);
}
Console.Read();
ConcurrentDictionary Pitfall - Are delegates factories from GetOrAdd and AddOrUpdate synchronized?
Extension methods to make ConcurrentDictionary GetOrAdd and AddOrUpdate thread safe when using valueFactory delegates