Thread Safety with Dictionary

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

If I have a

Dictionary myDic = new Dictionary
//Populate dictionary

One thread does

3条回答
  •  失恋的感觉
    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. *

提交回复
热议问题