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?
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.
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.
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.
The .NET 4.0 class that supports concurrency is named ConcurrentDictionary
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With