Search code examples
c#multithreadingthread-safetyreadonly-collectionireadonlydictionary

Can ReadOnlyDictionary be used when only the values are changing?


I know ReadOnlyDictionary is "thread-safe" when accessing from multiple threads as long as the collection isn't changing.
But what if the collection isn't changing (no keys are ever added/removed) and values are thread-safe by themselves, meaning, the reference will not change, but the value's internal data might (the Value object itself is thread safe) For example

ReadOnlyDictionary<Key, ThreadSafe Value> dictionary = new...  
dictionary[key].inc()

Where inc() is a thread safe method of ThreadSafeValue.

Since the collection itself isn't changing, and the references aren't changing, I'd think this is ok, but since ReadOnlyDictionary doesn't expose Add/Remove/Update and it's not thread safe, I wonder if my assumption is correct


Solution

  • Your issue seems to stem from a confusion of what a "value" is in the context of a dictionary.

    From the perspective of a dictionary, assuming ThreadSafeValue is a reference type, then the value is a reference to the object. If you never modify the dictionary, then the reference itself can never change. In other words, neither the key nor the value changes.

    If ThreadSafeValue itself is thread safe, then the whole use case appears safe.