为什么 ReadOnlyDictionary 不是线程安全的? [英] Why isn’t ReadOnlyDictionary thread-safe?
问题描述
我正在寻找可从多个线程访问的只读字典.虽然 ConcurrentDictionary 公开了这样的功能,但我不想有开销和奇怪的 API.
I’m looking for a readonly-dictionary to be accessed from multiple threads. While ConcurrentDictionary exposes such capabilities, I don’t want to have the overhead and the strange API.
.Net 4.5 在提供这样一个类的同时,文档指出只有静态调用是安全的.
.Net 4.5 while providing such a class, the documentation states that only static calls are safe.
不知道为什么?
推荐答案
ReadOnlyDictionary
只是任何其他字典的包装器.因此,它仅与底层字典一样线程安全.
ReadOnlyDictionary
is just a wrapper around any other dictionary. As such, it's only as thread-safe as the underlying dictionary.
特别是,如果有一个线程在修改底层字典而另一个线程从包装器读取,则无法保证安全.
In particular, if there's a thread modifying the underlying dictionary while another thread reads from the wrapper, there's no guarantee of safety.
如果您想要一个 ReadOnlyDictionary
从所有角度实际上是不可变的,您可以创建原始词典的副本,创建一个 ReadOnlyDictionary
包装它,然后不在任何地方保留对克隆的引用.随着only 读取操作的进行,它应该是线程安全的.当然,如果键或值类型是可变的,那就会带来第二层线程不安全"的担忧.
If you want a ReadOnlyDictionary
which is effectively immutable from all angles, you can create a clone of the original dictionary, create a ReadOnlyDictionary
wrapper around that, and then not keep a reference to the clone anywhere. With only read operations going on, it should then be thread-safe. Of course, if the key or value types are mutable, that opens up a second degree of "thread-unsafety" to worry about.
这篇关于为什么 ReadOnlyDictionary 不是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!