Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn’t ReadOnlyDictionary thread-safe?

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?

like image 910
Mouk Avatar asked Dec 03 '12 13:12

Mouk


1 Answers

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.

like image 177
Jon Skeet Avatar answered Sep 28 '22 06:09

Jon Skeet