ConcurrentDictionary enumeration and locking

前端 未结 1 1105
生来不讨喜
生来不讨喜 2021-01-17 07:18

If I have a ConcurrentDictionary, do I need to lock it when looping thru it using foreach?

相关标签:
1条回答
  • 2021-01-17 08:10

    If I have a ConcurrentDictionary, do I need to lock it when looping thru it using foreach?

    No. From the docs for 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.

    0 讨论(0)
提交回复
热议问题