Why isn’t ReadOnlyDictionary thread-safe?

自古美人都是妖i 提交于 2019-12-23 07:19:26

问题


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 while providing such a class, the documentation states that only static calls are safe.

I wonder why?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/13684143/why-isn-t-readonlydictionary-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!