Furkan Gözükara
Furkan Gözükara

Reputation: 23830

Is ConcurrentDictionary ContainsKey method synched?

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

Upvotes: 12

Views: 11393

Answers (1)

user2864740
user2864740

Reputation: 61885

"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.

Upvotes: 12

Related Questions