为什么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
可以从 all 角度有效地不变,则可以创建原始词典的副本,在其周围创建一个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屋!