正在访问 Dictionary<TKey, TValue>键属性线程安全吗? [英] Is accessing the Dictionary&lt;TKey, TValue&gt; Keys property thread safe?

查看:37
本文介绍了正在访问 Dictionary<TKey, TValue>键属性线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我可以去吗:

string[] keys = new string[items.Count];
items.Keys.CopyTo(keys);

其中 items 是:

Where items is a:

Dictionary<string, MyObject>

可能被另一个线程修改的实例?(我不清楚在访问 Keys 属性时 Dictionary 的内部工作是否会迭代集合 - 在这种情况下,我知道它不是线程安全的).

instance that could be being modified by another thread? (Its not clear to me if when accessing the Keys property the inner workings of Dictionary iterates the collection - in which case I know it would not be thread safe).

更新:我意识到我上面的例子不是线程安全的,因为 Dictonary 的大小可能会在两行之间发生变化.但是呢:

Update: I realise my above example is not thread safe becuase the size of the Dictonary could change between the lines. however what about:

Dictionary<string, MyObject> keys = items.Keys;
string[] copyOfKeys = new string[keys.Count];
keys.Keys.CopyTo(copyOfKeys );

推荐答案

不,Dictionary 不是线程安全的.如果您需要线程安全并且使用 .NET 4 或更高版本,则应使用 ConcurrentDictionary.

No, Dictionary is not thread-safe. If you need thread safety and you're using .NET 4 or higher, you should use a ConcurrentDictionary.

来自 MSDN:

一个字典可以同时支持多个阅读器,只要不修改集合.即便如此,枚举通过集合本质上不是线程安全的过程.在枚举与写访问争用的罕见情况,在整个枚举过程中必须锁定集合.为了让多个线程访问的集合进行读写,您必须实现自己的同步.

A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

这篇关于正在访问 Dictionary<TKey, TValue>键属性线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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