Why isn't ReadOnlyDictionary thread safe?

I need access to readonly-dictionary from multiple threads. Although ConcurrentDictionary provides such capabilities, I don't want to have overhead and a weird API.

.Net 4.5, by providing such a class, the documentation states that only static calls are safe.

I wonder why?

+7
source share
1 answer

ReadOnlyDictionary is just a wrapper around any other dictionary. As such, it is only as thread-safe, as the main dictionary.

In particular, if there is a thread that changes the underlying dictionary when another thread is read from the wrapper, there is no security guarantee.

If you want ReadOnlyDictionary , which is effectively unchanged on all sides, you can create a clone of the original dictionary, create a wrapper around it ReadOnlyDictionary , and then not store the link to the clone anywhere. When only read operations are performed, it must be thread safe. Of course, if the key or value types are mutable, this opens up a second degree of thread-insecurity, which you need to worry about.

+8
source

All Articles