Can ConcurrentDictionary.TryAdd fail?

Dave Lawrence picture Dave Lawrence · Jul 16, 2012 · Viewed 29.3k times · Source

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

Answer

oleksii picture oleksii · Jul 16, 2012

Yes it can, here are the conditions (from msdn):

  • ArgumentNullException - when the key is null reference
  • OverflowException - when max number of elements was reached
  • It returns false if an element with the same key already exist

Just to reiterate, this is nothing to do with concurrency. If you worry about two threads inserting an item at the same time then the following can happen:

  • Both inserts work fine, if the keys are different.
  • One insert works fine and returns true, the other insert fails (with no exception) and returns false. This happens if two threads try to insert an item with the same key and basically only one would win and the other would lose.