❔ is a non-concurrent dictionary concurrent safe under alterations of only value?
Dictionary<string,object> ds;
string x; object z;
var y=ds[x]; // we know 'x' exists as a key.
ds[x]=z; // is it safe to change key x to a different value?
I don't care if other threads see either y or z under this scenario. All i care about is not getting runtime exceptions, or nonsensical results (eg, value for wrong key returned).
I know that modifying the keys in any way is very much not concurrent safe, and is handled correctly.
4 Replies
It's best to just use a concurrent dictionary for this to get rid of the risk of something happening at all
ConcurrentDictionary uses fine-grained locking which guarantees no more than one thread will access a single element at a time while leaving all other elements unlocked
ConcurrentDictionary Class (System.Collections.Concurrent)
Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.
Save yourself some hair too without having to worry about async access to a not thread-safe object
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.