title: .net Dictionary.Resize() exception - thread safety?
body: <p><br>
  We have a very serious problem that's causing thousands of exceptions per minute. We've got a website that runs a home-grown caching mechanism that holds data in the form of:</p>
  
  <pre><code>protected static IDictionary&lt;int, IList&lt;IInterfaceForData&gt;&gt; m_Data = null;
  </code></pre>
  
  <p>and when we call Add on this dictionary, we get a very bizarre behavior: "<strong>Index was outside the bounds of the array</strong>", when the key was 100% not in the dictionary:</p>
  
  <pre><code>m_Data.Add(id, new List&lt;IInterfaceForData&gt;());
  </code></pre>
  
  <p>We protect this call using a lock like this:</p>
  
  <pre><code>if(Monitor.TryEnter(m_LockObj, 1000))
  {
     try
     {
         m_Data.Add(id, new List&lt;IInterfaceForData&gt;());
     }
     catch(Exception ex)
     {                                   
          // log exception
     }
     finally
     {
        Monitor.Exit(m_LockObj);
     }
  }
  </code></pre>
  
  <p>and we get this exception:</p>
  
  <pre><code>   at System.Collections.Generic.Dictionary`2.Resize()     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>We can't find any explanation for this because the exception is related to Dictionary's thread safety, and we (think we) are thread safe. We use lock() or Monitor.TryEnter on every Add() and Remove() calls, except for m_Data.TryGetValue(...)</p>
  
  <p>Any help would be greatly appreciated.</p>
  
  <p>thanks a lot.</p>