Thread Safety with Dictionary

后端 未结 3 972
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-13 20:23

If I have a

Dictionary myDic = new Dictionary
//Populate dictionary

One thread does

相关标签:
3条回答
  • 2021-02-13 20:34

    You will only get InvalidOperationException: Collection was modified if you enumerate the dictionary while modifying.

    However, that is not thread-safe.
    If one of those operations causes the dictionary to resize, the other one may get lost.
    Instead, use ConcurrentDictionary.

    0 讨论(0)
  • 2021-02-13 20:41

    To improve your code, you might want to look up the ConcurrentDictionary class. It will solve some problems with multi-threading.

    0 讨论(0)
  • 2021-02-13 20:45

    System.Collections.Generic collections are only thread safe if you are reading from multiple threads.

    Quoting from MSDN

    System.Collections.Generic collection classes do not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently

    If you want want thread safety for both read and write operations consider using System.Collections.Concurrent

    *When you write new code, use the concurrent collection classes whenever the collection will be writing to multiple threads concurrently. *

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