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
CodePudding user response:
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.
CodePudding user response:
Yes, your assumption is correct. Since the values stored in the dictionary are autonomously thread-safe, and the dictionary itself is practically immutable, the whole data structure is thread safe.