Why lock when reading from a dictionary Why lock when reading from a dictionary multithreading multithreading

Why lock when reading from a dictionary


The Dictionary<TKey, TValue> class is not threadsafe.

If one thread writes one key to the dictionary while a different thread reads the dictionary, it may get messed up. (For example, if the write operation triggers an array resize, or if the two keys are a hash collision)

Therefore, the code uses a lock to prevent concurrent writes.


There is a benign race condition when writing to the dictionary; it is possible, as you stated, for two threads to determine there is not a matching entry in the cache. In this case, both of them will read from the DB and then attempt to insert. Only the object inserted by the last thread is kept; the other object will be garbage collected when the first thread is done with it.

The read to the dictionary needs to be locked because another thread may be writing at the same time, and the read needs to search over a consistent structure.

Note that the ConcurrentDictionary introduced in .NET 4.0 pretty much replaces this kind of idiom.


That's a common practice to access any non thread safe structures like lists, dictionaries, common shared values, etc.

And answering main question: locking a read we guarantee that dictionary will not be changed by another thread while we are reading its value. This is not implemented in dictionary and that is why it’s called non thread safe :)