5

I have a dictionary only supports add and modify operations and can be concurrently operated, but always for different keys. Keys are int and values are a reference type. Also modify means change some properties of a value.

My questions are:

  1. Do I need to use ConcurrentDictionary in this scenario? If needed, how does it help?
  2. If concurrent modification can happen on the same key, will ConcurrentDictionary help to ensure thread safty? My understanding is no, is that correct?

Thanks!

Green Falcon
  • 818
  • 3
  • 17
  • 48
Student222
  • 3,021
  • 2
  • 19
  • 24
  • 1. Yes, you need to use it. 2. ["All these operations are atomic and are thread-safe with regards to all other operations on the ConcurrentDictionary class. The only exceptions are the methods that accept a delegate, that is, AddOrUpdate and GetOrAdd."](https://msdn.microsoft.com/en-us/library/dd287191(v=vs.110).aspx#Anchor_7) We still need a "please read the docs aloud to me" tag. – 15ee8f99-57ff-4f92-890c-b56153 Oct 11 '16 at 13:36
  • 1
    What did you find when you looked at the documentation for each of those types with respect to whether or not these operations are valid? How did the information you find there fail to answer these questions? – Servy Oct 11 '16 at 13:37
  • @EdPlunkett Thank you. By reading the docs and other SO answers, I think I get it for the first question. Yes, I need to use Concurrent version. Because when concurrent add, the dict may resize, and that will cause issues. But for the second question, I am still not very clear. I think even use the concurrent version. When I concurrently modify properties in side a value, I still need to lock the value. Is that true? Thanks! – Student222 Oct 11 '16 at 14:36

2 Answers2

2

Do I need to use ConcurrentDictionary in this scenario? If needed, how does it help?

Yes, the standard dictionary will not behave correctly if more than one thread adds or removes entries at the same time. (although it is safe for multiple threads to read from it at the same time if no others are modifying it).

If concurrent modification can happen on the same key, will ConcurrentDictionary help to ensure thread safety? My understanding is no, is that correct?

If you are asking "Will the concurrent dictionary prevent multiple threads from accessing the values inside the dictionary at the same time?", then no, it will not.

If you want to prevent multiple threads from accessing the same value at the same time you will need to use some sort of concurrency control, such as locking.

Jason Hernandez
  • 2,907
  • 1
  • 19
  • 30
0

Best way to find this out is check MSDN documentation.

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

Under thread safety section, it is stated "All public and protected members of ConcurrentDictionary<TKey, TValue> are thread-safe and may be used concurrently from multiple threads."

Enigmativity
  • 113,464
  • 11
  • 89
  • 172