Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ConcurrentDictionary.TryAdd fail?

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

like image 614
Dave Lawrence Avatar asked Jul 16 '12 09:07

Dave Lawrence


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 Dictionary thread-safe C#?

It is thread-safe and internally uses locking. It is useful in the case of a multi-threaded application. However, ConcurrentDictionary is slower than Dictionary.

What is a concurrent dictionary?

adjective. occurring or existing simultaneously or side by side: concurrent attacks by land, sea, and air. acting in conjunction; cooperating: the concurrent efforts of several legislators to pass the new law. having equal authority or jurisdiction: two concurrent courts of law.


1 Answers

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.
like image 137
oleksii Avatar answered Sep 17 '22 13:09

oleksii