Thread Safety with Dictionary

家住魔仙堡 提交于 2019-12-04 17:35:52

问题


If I have a

Dictionary<int, StreamReader> myDic = new Dictionary<int, StreamReader>
//Populate dictionary

One thread does

myDic[0] = new StreamReader(path);

Another thread does

myDic[1] = new StreamReader(otherpath)

Is this thread safe because the actual item in the dictionary getting modified is different to the one on the other thread or will I get a InvalidOperationException: Collection was modified


回答1:


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.




回答2:


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. *




回答3:


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



来源:https://stackoverflow.com/questions/8182945/thread-safety-with-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!