嵌套字典对于父 ConcurrentDictionary 线程安全吗?
如果我有一个 ConcurrentDictionary 对象 ConcurrentDictionary
,则嵌套的 Dictionary
会被锁定正在外部 ConcurrentDictionary 上执行操作吗?
场景:外部ConcurrentDictionary
outerDict
正在执行
outerDict.Add(42, new Dictionary
在一个线程上,并且在另一个线程上(同时),内部 Dictionary
正在执行
outerDict[30].Add("hello", “世界”)
。
在上述场景中,对于外部 ConcurrentDictionary
和嵌套 Dictionary
的修改是否都应用了并发,或者这两个操作同时执行?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然不是,它们是具有不同访问规则的不同词典。
不过,您的示例很好,因为您正在从不同的线程访问不同的字典。如果您这样做:
您很快就会遇到问题。
Of course not, they're different dictionaries with different access rules.
Your example however is fine, because you're accessing different dictionaries from different threads. If you were to do this instead:
You'd quickly run into issues.
这里有4个操作:
There are 4 operations here:
ConcurrentDictionary
是线程安全的。它的设计使多个线程可以安全地使用该字典中的键。它不能也不会将该线程安全性扩展到存储在字典中的值。并发字典存储对内部字典的引用。但内部词典并不“知道”任何引用它的内容。据它所知,它只是一个
Dictionary
。尽管并发字典具有对内部字典的引用,但它不以任何方式“拥有”或控制该内部字典。
您可以编写以下代码:
在这种情况下,
innerDictionary
仍然保留对该字典的引用。它可以将其作为参数传递给另一个方法。并发字典可能会超出范围并被垃圾收集,而其他一些对象则维护对内部字典的引用。要点是,除了持有对象引用的并发字典之外,它不会以其他方式控制该对象的行为。
A
ConcurrentDictionary<TKey, TValue>
is thread safe. It's designed so that multiple threads can safely work with the keys in that dictionary. It cannot and does not extend that thread safety to the values stored in the dictionary.The concurrent dictionary stores a reference to the inner dictionary. But the inner dictionary doesn't "know" about anything that references it. As far as it knows it's just a
Dictionary<string, string>
.Although the concurrent dictionary has a reference to the inner dictionary, it doesn't in any way "own" or control that inner dictionary.
You could write this code:
In this case
innerDictionary
still maintains a reference to that dictionary. It can pass it as an argument to another method. The concurrent dictionary could go out of scope and get garbage collected while some other object maintains a reference to the inner dictionary.The point is that other than the concurrent dictionary holding a reference to an object, it doesn't otherwise control the behavior of that object.