Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is locking necessary for Dictionary lookup?

lock(dictionaryX)
{
   dictionaryX.TryGetValue(key, out value);
}

is locking necessary while doing lookups to a Dictionary ?

THe program is multithreaded, and while adding key/value to dict. dict is being locked.

like image 972
DarthVader Avatar asked Oct 22 '10 19:10

DarthVader


People also ask

Do you need to lock concurrent Dictionary?

ConcurrentDictionary<TKey,TValue> is designed for multithreaded scenarios. You do not have to use locks in your code to add or remove items from the collection. However, it is always possible for one thread to retrieve a value, and another thread to immediately update the collection by giving the same key a new value.

Is Dictionary read thread-safe?

A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration.

Is ConcurrentDictionary slower?

ConcurrentDictionary - "Good read speed even in the face of concurrency, but it's a heavyweight object to create and slower to update."


2 Answers

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.

like image 121
Kamyar Avatar answered Sep 21 '22 20:09

Kamyar


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.

like image 33
Jesse C. Slicer Avatar answered Sep 24 '22 20:09

Jesse C. Slicer