Student222
Student222

Reputation: 3061

C# Dictionary concurrent add or modify only for different keys, is ConcurrentDictionary necessary?

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!

Upvotes: 5

Views: 3923

Answers (2)

Jason Hernandez
Jason Hernandez

Reputation: 2969

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.

Upvotes: 2

Mitesh Prajapati
Mitesh Prajapati

Reputation: 53

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."

Upvotes: 0

Related Questions