问题很简单:为什么线程安全字典允许数据竞争,因为该字典中的所有方法都是原子的,并且两个线程不应该接收相同的值?
在下面的示例中,可以显示至少10个、至少12个、至少14个。
public class Program
{
private static ConcurrentDictionary<string, int> _map = [];
static async Task Main(string[] args)
{
_map["air"] = 0;
var tasks = new List<Task>();
for (int i = 0; i < 10000; i++)
{
tasks.Add(Task.Run(() =>
{
for (int i = 0; i < 10; i++)
{
_map.TryGetValue("air", out int value);
_map.AddOrUpdate("air", value, (key, oldValue) => oldValue + 1);
_map.TryGetValue("air", out int newValue);
if (newValue >= 10)
{
_map.TryRemove("air", out _);
_map.TryAdd("air1", newValue);
}
}
}));
}
await Task.WhenAll(tasks);
Console.WriteLine(_map["air1"]);
}
}




