Will it only return false if the dictionary does not contain a value for the given key or will it also return false due to thread race conditions, like another thread adds/updates something?
Question in code:
ConcurrentDictionary<int, string> cd = new ConcurrentDictionary<int, string>(); // This might fail if another thread is adding with key value of 1. cd.TryAdd(1, "one"); // Will this ever fail if no other thread ever removes with the key value of 1? cd.TryRemove(1);
Edit: I think that it only will return false if it does not contain a value for the given key, but want to be absolutely sure.
To retrieve single item, ConcurrentDictionary provides TryGetValue method. We have to provide Key in the TryGetValue method. It takes the out parameter to return the value of key. TryGetValue returns true if key exists, or returns false if key does not exists in dictionary.
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.
Concurrent. ConcurrentDictionary<TKey,TValue>. This collection class is a thread-safe implementation. We recommend that you use it whenever multiple threads might be attempting to access the elements concurrently.
While Mitch is right that a ConcurrentDictionary
is not vulnerable to race conditions, I think the answer to the question you are asking is that yes, if the key is present, TryRemove
will work and will return true
.
In the code you posted, there's no way that TryRemove
would return false
since cd
is a local variable not accessed anywhere else. But if some code elsewhere were given a reference to this ConcurrentDictionary
object and were removing keys on a separate thread, then it's possible that TryRemove
could return false
, even here -- but only because the key was already removed, not because some other action is being performed on the dictionary and the key is somehow "stuck" there.
The ConcurrentDictionary does not suffer from race conditions. That's why you use it.
Return Value
true if an object was removed successfully; otherwise, false.
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