lock(dictionaryX)
{
dictionaryX.TryGetValue(key, out value);
}
is locking necessary while doing lookups to a Dictionary ?
THe program is
Yes you need to lock the dictionary for access in a multithreaded environment. The writing to a dictionary is not atomic, so it could add the key, but not the value. In that case when you access it, you could get an exception.
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.
Yes, you should lock if this dictionary is a shared resource between more than one thread. This ensures that you get the correct value and other thread doesn't happen to change value mid-way during your Lookup call.
If you are on .Net 4, you can replace with ConcurrentDictionary to do this safely. There are other similar collections, preferred when you need multithreaded access, in the System.Collection.Concurrent namespace.
Don't use roll-your-own locking if this is an option for you.
Yes, you have to lock if you have multithreaded updates on that dictionary. Check this great post for details: “Thread safe” Dictionary(TKey,TValue)
But since ConcurrentDictionary<> introduced you can use it either via .NET 4 or by using Rx in 3.5 (it contains System.Threading.dll with implementation for new thread-safe collections)
Use the new ConcurrentDictionary<TKey, TValue> object and you can forget about having to do any locks.