如果我有一个
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)
这是线程安全的,因为得到修改,在字典中的实际产品不同的一个接一个的线程上,否则我将得到一个 InvalidOperationException异常:集合已修改
您只能获得 InvalidOperationException异常:集合已修改
如果您枚举的字典而修改。
You will only get InvalidOperationException: Collection was modified
if you enumerate the dictionary while modifying.
不过,这不是线程安全的。照片
如果这些行动之一导致的字典来调整,另外一个可能会丢失。
相反,使用 ConcurrentDictionary
。
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
.