title: Correct way to lock the dictionary object
body: <p>In my code I have a static dictionary object </p>
  
  <pre><code>private static IDictionary&lt; ConnKey, DbConnection &gt; ConnectionList = new Dictionary&lt; ConnKey, DbConnection &gt;( );
  </code></pre>
  
  <p>which is throwing this error</p>
  
  <pre><code>System.IndexOutOfRangeException: Index was outside the bounds of the array.
    at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
    at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
  </code></pre>
  
  <p>I searched and found that this occurs because multiple threads try to access dictionary, but I do have <code>lock</code> on dictionary</p>
  
  <pre><code>lock( ConnectionList ) {
     ConnectionList.Add( key, res );
  }
  </code></pre>
  
  <p>Then I searched more and found that lock on dictionary doesn't prevent all the operations on it so I should be using <code>lock</code> on <code>SyncRoot</code> object of it like this to achieve what I want</p>
  
  <pre><code>lock( ((IDictionary)ConnectionList).SyncRoot) {
  </code></pre>
  
  <p>But then I searched that using <code>SyncRoot</code> is not a good practice </p>
  
  <p>On further search I found there is a <code>ConcurrentDictionary</code> for this purpose</p>
  
  <ol>
  <li>So can anybody please suggest me which is the best way to lock the dictionary </li>
  <li>If I use <code>ConcurrentDictionary</code> do I still need to use <code>lock</code> on it or will it handle everything by itself.</li>
  <li>If I have to use lock on <code>ConcurrentDictionary</code>, I have to use <code>lock</code> on it directly or again I have to lock the <code>SyncRoot</code> object for it</li>
  </ol>
  
  <p>Thanks in advance!</p>