没事的时候自己做了个实验,就针对.net 4.0里ConcurrentDictionary的AddOrUpdate方法,发现在少数情况下,会出现冲突。

 

static ConcurrentDictionary<string, int> dic = new ConcurrentDictionary<string, int>();

static void Main(string[] args)
{
new Thread(() => Test(1)).Start();
new Thread(() => Test(2)).Start();
new Thread(() => Test(3)).Start();
new Thread(() => Test(4)).Start();

Console.ReadLine();
}

public static void Test(int thread)
{
var startTime
= DateTime.Now;

for (int i = 0; i < 10000; i++)
{
try
{
Thread.Sleep(
1);

dic.AddOrUpdate(
"Test", 1, (k, v) => v + 1);
}
catch (Exception ex)
{
Console.WriteLine(
string.Format("线程{0}发生异常:", thread, ex.Message));
}
}

Console.WriteLine(
string.Format("线程{0}结果为{1},耗时{2}ms", thread, dic["Test"], DateTime.Now.Subtract(startTime).TotalMilliseconds));
}

 

理论上来说这个方法最后一个线程返回的结果应该是40000,不过偶尔会出现这种情况:

 

 

求解。