Is ConcurrentDictionary ContainsKey method synched?

MonsterMMORPG picture MonsterMMORPG · Aug 20, 2014 · Viewed 7.5k times · Source

Simple question Assume that i have a ConcurrentDictionary

I use TryAdd and ContainsKey methods

Now assume that from 100 threads i started to process stuff. Assume that when 3 threads while adding a new key with TryAdd method another 3 threads asking whether key exists or not with ContainsKey method

Do ContainsKey wait those 3 threads adding process before returning me result ?

Or they are not synched i mean that one of those 3 threads could be adding the key i am asking with ContainsKey method however since the process is not done yet the answer i was gonna get would be false

Ty very much for answers C# WPF .net 4.5 Latest

Answer

user2864740 picture user2864740 · Aug 20, 2014

"No" (see Sam's comment), furthermore there is no atomic guard established by ContainsKey across other access or method calls to the ConcurrentDictionary.

That is, the following code is broken

// 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);
}

and the Try* methods should be used consistently instead

cd.TryAdd("x", y);

If further synchronization (or atomicity) needs to be guaranteed past the specialized concurrent methods then a larger monitor/lock context should be established.