is locking necessary for Dictionary lookup? is locking necessary for Dictionary lookup? multithreading multithreading

is locking necessary for Dictionary lookup?


As mentioned here:

Using TryGetValue() without locking is not safe. The dictionary is temporarily in a state that makes it unsuitable for reading while another thread is writing the dictionary. A dictionary will reorganize itself from time to time as the number of entries it contains grows. When you read at the exact time this re-organization takes place, you'll run the risk of finding the wrong value for the key when the buckets got updated but not yet the value entries.

UPDATE: take a look at "Thread Safety" part of this page too.


As with many subtle questions in programming, the answer is: Not necessarily.

If you only add values as an initialization, then the subsequent reading does not need to be synchronized. But, on the other hand, if you're going to be reading and writing at all times, then absolutely you need to protect that resource.

However, a full-blown lock may not be the best way, depending on the amount of traffic your Dictionary gets. Try a ReaderWriterLockSlim if you are using .NET 3.5 or greater.


If you have multiple threads accessing the Dictionary, then you do need to lock on updates and on lookup. The reason you need to lock on lookup is that there could be an update taking place at the same time you're doing the lookup, and the Dictionary could be in an inconsistent state during the update. For example, imagine that your have one thread doing this:

if (myDictionary.TryGetValue(key, out value)){}

and a separate thread is doing this:

myDictionary.Remove(key);

What could happen is that the thread doing the TryGetValue determines that the item is in the dictionary, but before it can retrieve the item, the other thread removes it. The result would be that the thread doing the lookup would either throw an exception or TryGetValue would return true but the value would be null or possibly an object that does not match the key.

That's only one thing that can happen. Something similarly disastrous can happen if you're doing a lookup on one thread and another thread does an add of the value that you're trying to look up.