title: What's the best way of implementing a thread-safe Dictionary?
body: <p>I was able to implement a thread-safe Dictionary in C# by deriving from IDictionary and defining a private SyncRoot object:</p>
  
  <pre><code>public class SafeDictionary&lt;TKey, TValue&gt;: IDictionary&lt;TKey, TValue&gt;
  {
      private readonly object syncRoot = new object();
      private Dictionary&lt;TKey, TValue&gt; d = new Dictionary&lt;TKey, TValue&gt;();
  
      public object SyncRoot
      {
          get { return syncRoot; }
      } 
  
      public void Add(TKey key, TValue value)
      {
          lock (syncRoot)
          {
              d.Add(key, value);
          }
      }
  
      // more IDictionary members...
  }
  </code></pre>
  
  <p>I then lock on this SyncRoot object throughout my consumers (multiple threads):</p>
  
  <p>Example:</p>
  
  <pre><code>lock (m_MySharedDictionary.SyncRoot)
  {
      m_MySharedDictionary.Add(...);
  }
  </code></pre>
  
  <p>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?</p>