Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 815
MonsterMMORPG Avatar asked Aug 20 '14 00:08

MonsterMMORPG


People also ask

What is the purpose of the ConcurrentDictionary TKey TValue class?

Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.

How does ConcurrentDictionary work in C#?

ConcurrentDictionary is thread-safe collection class to store key/value pairs. It internally uses locking to provide you a thread-safe class. It provides different methods as compared to Dictionary class. We can use TryAdd, TryUpdate, TryRemove, and TryGetValue to do CRUD operations on ConcurrentDictionary.

Is ConcurrentDictionary ordered?

No. The list order of ConcurrentDictionary is NOT guaranteed, lines can come out in any order.

Is ConcurrentDictionary slow?

In . Net 4, ConcurrentDictionary utilized very poor locking management and contention resolution that made it extremely slow. Dictionary with custom locking and/or even TestAndSet usage to COW the whole dictionary was faster.


1 Answers

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

like image 131
user2864740 Avatar answered Nov 09 '22 07:11

user2864740