Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way of implementing a thread-safe Dictionary?

I was able to implement a thread-safe Dictionary in C# by deriving from IDictionary and defining a private SyncRoot object:

public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue> {     private readonly object syncRoot = new object();     private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>();      public object SyncRoot     {         get { return syncRoot; }     }       public void Add(TKey key, TValue value)     {         lock (syncRoot)         {             d.Add(key, value);         }     }      // more IDictionary members... } 

I then lock on this SyncRoot object throughout my consumers (multiple threads):

Example:

lock (m_MySharedDictionary.SyncRoot) {     m_MySharedDictionary.Add(...); } 

I was able to make it work, but this resulted in some ugly code. My question is, is there a better, more elegant way of implementing a thread-safe Dictionary?

like image 788
GP. Avatar asked Oct 01 '08 14:10

GP.


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.

Are Python dict threads safe?

Many common operations on a dict are atomic, meaning that they are thread-safe. Atomic means that the operation either occurs or does not occur with no in between inconsistent state. Operations such as adding, removing, and reading a value on a dict are atomic.

Is Dictionary Trygetvalue thread-safe?

a) This is not thread-safe, as the underlying Dictionary itself is not thread safe. If another thread is calling Add at the same time, undefined behavior can occur.


1 Answers

The .NET 4.0 class that supports concurrency is named ConcurrentDictionary.

like image 151
Hector Correa Avatar answered Oct 19 '22 07:10

Hector Correa