ConcurrentDictionary ContainsKey方法是同步的吗?

Mon*_*RPG 6 c# multithreading concurrentdictionary

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

我使用TryAddContainsKey方法

现在假设从100个线程我开始处理东西.假设3个线程在添加新密钥时使用TryAdd方法另外3个线程询问密钥是否存在与ContainsKey方法有关

不要ContainsKey等到那些3个线程返回我结果之前加入的过程?

或者他们没有同步,我的意思是这3个线程中的一个可能正在添加我用ContainsKey方法询问的密钥但是由于该过程尚未完成,我将得到的答案将是假的

Ty非常感谢答案C#WPF .net 4.5最新

use*_*740 9

"不"(参见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);
}
Run Code Online (Sandbox Code Playgroud)

并且Try*应该始终如一地使用这些方法

cd.TryAdd("x", y);
Run Code Online (Sandbox Code Playgroud)

如果需要通过专用并发方法保证进一步的同步(或原子性),则应建立更大的监视/锁定上下文.

  • -1:我用粗体解释了这个问题:"``ContainsKey`是否包含一个同步调用,这会导致它等到`tryAdd`调用完成后再返回它的答案?" 这个问题的答案是"不".并发集合与使用锁定进行同步的集合非常不同; 它们尽可能避免锁定,通常采用[无锁或无等待算法](http://rethinkdb.com/blog/lock-free-vs-wait-free-concurrency/). (3认同)
  • @ 280Z28很好的观察.我已经更新了有关评论的初步措辞.另外,作为支持推理,`ContainsKey`在内部使用TryGetValue(参考.[来自grepcode的ConcurrentDictionary.cs](http://www.dotnetframework.org/default.aspx/4@0/4@0/untmp/DEVDIV_TFS/Dev10 /发布/ RTMRel/NDP/CLR/src目录/ BCL /系统/收藏/并行/ ConcurrentDictionary @ CS/1305376/ConcurrentDictionary @ CS)). (2认同)
  • 我删除了我的-1票,但由于它被引用,所以留下了评论.这是一个更好的链接:http://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentDictionary.cs#382 (2认同)