Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent Dictionary AddOrUpdate vs Index Add

Tags:

c#

There are two ways I've assigned values to a existing key in a concurrent dictionary in my current project.

A. concurrentDictionary1[key] = value;

and

B. concurrentDictionary2.AddOrUpdate(key, value, (k, v) => value);

If I know that the 'key' exists, are these functionally equivalent?

Is protection offered by the concurrency of the Concurrent Dictionary bypassed with method 'A'?

What is the difference here? What are the reasons for choosing one over the other?

I looked through the documentation at msdn, and it seems they only initialize a concurrent dictionary with method 'A', not update it.

like image 357
Bob2Chiv Avatar asked Jul 29 '13 14:07

Bob2Chiv


People also ask

Is ConcurrentDictionary indexer thread-safe?

It is thread-safe in the sense that the internal state of the ConcurrentDictionary will not be corrupted. This is the main guarantee offered by this class.

Is ConcurrentDictionary AddOrUpdate thread-safe?

It is thread safe in your usage. It becomes not thread safe when the delegate passed to AddOrUpdate has side effects, because those side effects may be executed twice for the same key and existing value.

What is the purpose of the Concurrent Dictionary TKey TValue class?

ConcurrentDictionary<TKey, TValue> Class Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.


1 Answers

This is an old question, but no one answered why you would use one over the other.

Choose A (the indexer) if you want to add or update and the update is not dependent on the existing value.

Choose B (AddOrUpdate) if you want to add or update and the update depends on an existing value. AddOrUpdate will do the update atomically.

So in the case in the question, you want to use the indexer. It's simpler, easier to read, and probably faster since you aren't creating an anonymous function.

like image 104
Garrett Greer Avatar answered Sep 29 '22 07:09

Garrett Greer