并发字典枚举和锁定 [英] ConcurrentDictionary enumeration and locking

查看:74
本文介绍了并发字典枚举和锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有ConcurrentDictionary,使用 foreach 遍历时是否需要将其锁定?

If I have a ConcurrentDictionary, do I need to lock it when looping thru it using foreach?

推荐答案


如果我有ConcurrentDictionary,使用foreach循环访问时是否需要将其锁定?

If I have a ConcurrentDictionary, do I need to lock it when looping thru it using foreach?

否。从 ConcurrentDictionary.GetEnumerator 的文档中:

No. From the docs for ConcurrentDictionary.GetEnumerator:


从字典返回的枚举数可以安全地与字典进行读和写操作,但是它并不代表一个时刻-字典的实时快照。通过枚举器公开的内容可能包含在调用GetEnumerator之后对字典所做的修改。

The enumerator returned from the dictionary is safe to use concurrently with reads and writes to the dictionary, however it does not represent a moment-in-time snapshot of the dictionary. The contents exposed through the enumerator may contain modifications made to the dictionary after GetEnumerator was called.

只要您对此感到满意,则不需要任何锁定。

As long as you're okay with that, you don't need any kind of locking.

这篇关于并发字典枚举和锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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