Proper use of parallel dictionary

I understand correctly that this is the correct use of a parallel 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); } //Seperate threads use this to update a value myDic[InputID] = newLongValue; 

I don't have locks, etc., and I'm just updating the value in the dictionary, although several threads may try to do the same.

+70
multithreading c # concurrency
Nov 22 '11 at 11:07
source share
5 answers

It depends on what you mean by thread safety.

From MSDN - How to add and remove items from ConcurrentDictionary :

ConcurrentDictionary<TKey, TValue> intended for multi-threaded scripts. You do not need 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, providing the same key with a new value.

Thus, you can get an inconsistent view of the value of an element in the dictionary.

+64
Nov 22 '11 at 11:17
source share

The best way to find out is to check the MSDN documentation.

For ConcurrentDictionary page http://msdn.microsoft.com/en-us/library/dd287191.aspx

The thread security section states: "All public and protected members of ConcurrentDictionary (Of TKey, TValue) are thread safe and can be used from multiple threads at the same time."

So, in terms of concurrency, you're fine.

+3
Nov 22 '11 at 11:25
source share

Yes you are right.

This and the ability to list a dictionary by one thread when changing it in another thread are the only means of existence for this class.

+2
22 Nov '11 at 11:13
source share

It depends, in my case I prefer to use this method.

 ConcurrentDictionary<TKey, TValue>.AddOrUpdate Method (TKey, Func<TKey, TValue>, Func<TKey, TValue, TValue>); 

See the MSDN Library for more information.

Sample Usage:

 results.AddOrUpdate( Id, id => new DbResult() { Id = id, Value = row.Value, Rank = 1 }, (id, v) => { v.Rank++; return v; }); 
+1
Nov 30 '15 at 13:09 on
source share

Just a note: it doesn't justify using a ConcurrentDicitonary object with a linear loop, which makes it underused. A better alternative is to follow the recommendations of the Microsoft Documentation, as mentioned by Oded using concurrency, according to the example below:

 Parallel.For(0, 4, i => { myDic.TryAdd(i, 0); }); 
0
May 24 '19 at 16:16
source share



All Articles