Why isn’t ReadOnlyDictionary thread-safe?

2019-06-16 02:56发布

问题:

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.