When ConcurrentDictionary TryRemove returns false

Will it return false only if the dictionary does not contain a value for this key or will it also return false due to the conditions of the thread race, for example, does another thread add / update 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 it will return false only if it does not contain a value for this key, but must be absolutely sure.

+57
c # concurrency
Aug 19 '10 at 7:14
source share
3 answers

While Mitch is right that ConcurrentDictionary not vulnerable to race conditions, I think the answer to the question you ask is that if the key is present, TryRemove will work and return true .

There is no way in the code you submitted to return TryRemove false , since cd is a local variable not accessible anywhere. But if some code elsewhere was given a reference to this ConcurrentDictionary object and deleted the keys in a separate thread, then it is possible that TryRemove can return false , even here, but only because the key has already been deleted , and not because some other action is performed in the dictionary, and the key somehow β€œgets stuck” there.

+60
Aug 19 '10 at 7:26
source share

ConcurrentDictionary does not suffer from race conditions. That is why you use it.

Return value

true if the object was deleted successfully; otherwise false.

+4
Aug 19 '10 at 7:17
source share

Another point:

 // This might fail if another thread is adding with key value of 1. cd.TryAdd(1, "one"); 

This comment is incorrect and may suffer from the same misconception about what it means to "try." This is not about a parallel attempt to add, whether the value has already been added using key 1 .

Consider the standard Dictionary<TKey,TValue> . The equivalent code would be:

 if (!d.Contains(1)) d.Add(1, "one"); 

This requires two operations. There is no way to create such an API to be thread safe, since cd can have a value with a key of 1 added between the Contains and Add calls, which then leads to the Add metallocation.

Parallel collections have APIs that logically combine these test pairs into single atomic operations in one API.

0
Oct 07 '17 at 20:09 on
source share



All Articles