title: How to show that the double-checked-lock pattern with Dictionary's TryGetValue is not threadsafe
body: <p>Recently I've seen some C# projects that use a double-checked-lock pattern on a <code>Dictionary</code>. Something like this:</p>
  
  <pre><code>private static readonly object _lock = new object();
  private static volatile IDictionary&lt;string, object&gt; _cache = 
      new Dictionary&lt;string, object&gt;();
  
  public static object Create(string key)
  {
      object val;
      if (!_cache.TryGetValue(key, out val))
      {
          lock (_lock)
          {
              if (!_cache.TryGetValue(key, out val))
              {
                  val = new object(); // factory construction based on key here.
                  _cache.Add(key, val);
              }
          }
      }
      return val;
  }
  </code></pre>
  
  <p>This code is incorrect,  since the <code>Dictionary</code> can be "growing" the collection in <code>_cache.Add()</code> while <code>_cache.TryGetValue</code> (outside the lock) is iterating over the collection. It might be extremely unlikely in many situations, but is still wrong.</p>
  
  <p>Is there a simple program to demonstrate that this code fails?</p>
  
  <p>Does it make sense to incorporate this into a unit test? And if so, how?</p>