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
Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.
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.
No. The list order of ConcurrentDictionary is NOT guaranteed, lines can come out in any order.
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.
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With