Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety of a Dictionary<TKey, TValue>

Tags:

c#

If I initialize a generic dictionary once, and no further adds/updates/removes are allowed, is it safe to have multiple threads reading from it with no locking (assuming that the dictionary is initialized before the readers are started)?

There is a note in the help for the non-generic HashTable that says that it is safe for multiple readers, but I did not see something similar for the Generic Dictionary.

like image 511
JMarsch Avatar asked Jan 11 '10 17:01

JMarsch


People also ask

Is a Dictionary thread-safe?

As you know, Microsoft in C# already provided a generic collection that is called Dictionary. So why do we need ConcurrentDictionary in C#? The answer is that ConcurrentDictionary provides a thread-safe functionality.

What is the purpose of the ConcurrentDictionary TKey TValue class?

Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.

Is Dictionary thread-safe in Python?

Python's built-in structures are thread-safe for single operations, but it can sometimes be hard to see where a statement really becomes multiple operations. Your code should be safe.


1 Answers

For your future reference, the documentation is here:

http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

It says:

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. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

like image 68
Eric Lippert Avatar answered Sep 20 '22 14:09

Eric Lippert