Can ConcurrentDictionary.TryAdd crash?

This is more of an academic question ... but can ConcurrentDictionary.TryAdd fail? And if so, in what cases and why?

+57
c # concurrentdictionary
Jul 16 2018-12-12T00:
source share
3 answers

Yes, maybe here are the conditions ( from MSDN ):

  • ArgumentNullException - when the key is a null reference
  • OverflowException - when the maximum number of items has been reached
  • Returns false if an item with the same key already exists.

Just to repeat, this has nothing to do with concurrency. If you are worried about two threads inserting an element at the same time, the following may happen:

  • Both inserts work fine if the keys are different.
  • One insert works fine and returns true, another insert fails (without exception) and returns false. This happens if two threads try to insert an element with the same key, and basically only one wins and the other loses.
+86
Jul 16 2018-12-12T00:
source share

Of course it is possible. If the key already exists, the method will return false.

Link: http://msdn.microsoft.com/en-us/library/dd267291.aspx

Return Value Type: System.Boolean true if the key / value pair was successfully added to ConcurrentDictionary. If the key already exists, this method returns false.

+7
Jul 16 2018-12-12T00:
source share

This will fail if the key already exists in the dictionary.

If the value cannot be added because you have run out of memory, you will get an exception.

+2
Jul 16 2018-12-12T00:
source share



All Articles