title: C# .NET 4.0 ConcurrentDictionary: TryRemove within a lock?
body: <p>I believe this works, I've tested it with multiple concurrent threads (though not exhaustively for race conditions and deadlocks):</p>
  
  <pre><code>public static System.Collections.Concurrent.ConcurrentDictionary&lt;string, item&gt; dict =
          new System.Collections.Concurrent.ConcurrentDictionary&lt;string, item&gt;();
  public static item dump;
  </code></pre>
  
  <p>...</p>
  
  <pre><code>foreach (System.Collections.Generic.KeyValuePair&lt;string, item&gt; x in dict)
  {
      lock (x.Value)
      {
          if (x.Value.IsCompleted)
          {
              dict.TryRemove(x.Key, out dump);
          }
      }
  }
  </code></pre>
  
  <p>This question is sort of a continuation of this question:</p>
  
  <p><a href="https://stackoverflow.com/questions/2318005/can-i-remove-items-from-a-concurrentdictionary-from-within-an-enumeration-loop-of">Can I remove items from a ConcurrentDictionary from within an enumeration loop of that dictionary?</a></p>
  
  <p>And this question:</p>
  
  <p><a href="https://stackoverflow.com/questions/2901289/updating-fields-of-values-in-a-concurrentdictionary">Updating fields of values in a ConcurrentDictionary</a></p>
  
  <p>In that I'm doing two "dicey" maneuvers:</p>
  
  <ol>
  <li>Removing values from a <code>ConcurrentDictionary</code> while at the same time enumerating through it (which seems to be ok).</li>
  <li>Locking the <code>Value</code> portion of a <code>ConcurrentDictionary</code>. Necessary because manipulating fields of the value is not thread safe, only manipulating the values themselves of the <code>ConcurrentDictionary</code> is thread safe (the code above is a snippet of a larger code block in which fields of values are actually manipulated).</li>
  </ol>