是否同步ConcurrentDictionary ContainsKey方法

本文关键字:方法 ContainsKey ConcurrentDictionary 同步 是否 | 更新日期: 2023-09-27 18:18:49

简单的问题假设我有一个ConcurrentDictionary

我使用TryAddContainsKey方法

现在假设从100个线程开始处理东西。假设当3个线程在用TryAdd方法添加一个新键时,另外3个线程用ContainsKey方法询问键是否存在

ContainsKey是否等待这3个线程添加进程,然后返回结果?

或者它们不同步我的意思是这三个线程中的一个可能正在添加我用ContainsKey方法询问的键但是由于这个过程还没有完成我将得到的答案将是false

c# WPF .net 4.5最新版

是否同步ConcurrentDictionary ContainsKey方法

"No"(参见Sam的评论),此外 ContainsKey在对ConcurrentDictionary的其他访问或方法调用中没有原子保护。

也就是说,下面的代码是破碎

// There is no guarantee the ContainsKey will run before/after
// different methods (eg. TryAdd) or that the ContainsKey and another
// method invoked later (eg. Add) will be executed as an atomic unit.
if (!cd.ContainsKey("x")) {
  cd.Add("x", y);
}

Try*方法应该一致使用,而不是

cd.TryAdd("x", y);

如果需要通过专门的并发方法来保证进一步的同步(或原子性),那么应该建立一个更大的监视器/锁上下文