Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When will ConcurrentDictionary TryRemove return false

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.

like image 627
Martin Ingvar Kofoed Jensen Avatar asked Aug 19 '10 07:08

Martin Ingvar Kofoed Jensen


People also ask

How do you find the value of ConcurrentDictionary?

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.

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.

Is ConcurrentDictionary thread-safe C#?

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.


2 Answers

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.

like image 143
Dan Tao Avatar answered Sep 20 '22 01:09

Dan Tao


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.

like image 45
Mitch Wheat Avatar answered Sep 22 '22 01:09

Mitch Wheat