Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent Dictionary Correct Usage

Am I right in thinking this is the correct use of a Concurrent Dictionary

private ConcurrentDictionary<int,long> myDic = new ConcurrentDictionary<int,long>();  //Main thread at program startup  for(int i = 0; i < 4; i++) {   myDic.Add(i, 0); }  //Separate threads use this to update a value  myDic[InputID] = newLongValue; 

I have no locks etc and am just updating the value in the dictionary even though multiple threads might be trying to do the same.

like image 205
Jon Avatar asked Nov 22 '11 11:11

Jon


People also ask

What is the difference between Dictionary and Concurrent Dictionary?

The name kind of explains it self. You use a ConcurrentDictionary when you need Concurrent access to a Dictionary. The thing to search for is "thread safety".

What is the purpose of Concurrent Dictionary?

ConcurrentDictionary<TKey,TValue> is designed for multithreaded scenarios. You do not have to use locks in your code to add or remove items from the collection. However, it is always possible for one thread to retrieve a value, and another thread to immediately update the collection by giving the same key a new value.

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

Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.

Is reading a Dictionary thread-safe?

A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure.


1 Answers

It depends on what you mean by thread-safe.

From MSDN - How to: Add and Remove Items from a ConcurrentDictionary:

ConcurrentDictionary<TKey, TValue> is designed for multithreaded scenarios. You do not have to use locks in your code to add or remove items from the collection. However, it is always possible for one thread to retrieve a value, and another thread to immediately update the collection by giving the same key a new value.

So, it is possible to get an inconsistent view of the value of an item in the dictionary.

like image 70
Oded Avatar answered Oct 13 '22 04:10

Oded