2

I'm confused about how Concurrent Dictionaries lock their resources.

For example, if I run a method that iterates over every item in the Dictionary and edits its value in a thread and I try to read the value of a key from another thread:

Will the second thread be accessing a snapshot of the Dictionary? If not, will it access the updated entry if that one has already been updated?

Alex Coronas
  • 468
  • 1
  • 6
  • 21
  • If you ever need a snapshot of a `ConcurrentDictionary` for whatever reason, use the [`ToArray`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2.toarray) method. The internal structures of the class will be locked while the snapshot is taken, so don't do it very frequently. – Theodor Zoulias Apr 04 '20 at 18:48

2 Answers2

2

Concurrent Dictionaries are thread-safe that can be accessed by multiple threads concurrently. Read operations on the dictionary are performed in a lock-free manner whereas write is protected with lock. For implementation details, please check ConcurrentDictionary.

S.N
  • 4,910
  • 5
  • 31
  • 51
0

The second thread will be accessing the updated dictionary. All a ConcurrentDictionary does is provide put a lock on the collection on any add or remove operations. Read operations are unaffected.

Source

simon-pearson
  • 1,601
  • 8
  • 10