Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 560
Student222 Avatar asked Nov 09 '22 07:11

Student222


1 Answers

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.

like image 187
Jason Hernandez Avatar answered Dec 09 '22 20:12

Jason Hernandez