线程安全与字典 [英] Thread Safety with Dictionary

查看:146
本文介绍了线程安全与字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个

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.

这篇关于线程安全与字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆