If I have a ConcurrentDictionary, do I need to lock it when looping thru it using foreach?
foreach
No. From the docs for ConcurrentDictionary.GetEnumerator:
ConcurrentDictionary.GetEnumerator
The enumerator returned from the dictionary is safe to use concurrently with reads and writes to the dictionary, however it does not represent a moment-in-time snapshot of the dictionary. The contents exposed through the enumerator may contain modifications made to the dictionary after GetEnumerator was called.
As long as you're okay with that, you don't need any kind of locking.
2.1m questions
2.1m answers
60 comments
57.0k users