title: Using a hashtable inside a Parallel.ForEach?
body: <p>I have a Parallel.ForEach loop running an intensive operation inside the body.</p>
  
  <p>The operation can use a Hashtable to store the values, and can be reused for other consecutive loop items. I add to the Hashtable after the intensive operation is complete, the next loop item can look up in the Hashtable and reuse the object, instead of running the intensive operation again.</p>
  
  <p>However, because I am using Parallel.ForEach there is a unsafe issue, causing the Hashtable.Add and the ContainsKey(key) calls go out of sync, as they might be running in parallel. Introducing locks may cause perf issues.</p>
  
  <p>Here's the sample code:</p>
  
  <pre><code>Hashtable myTable = new Hashtable;
  Parallel.ForEach(items, (item, loopState) =&gt;
  {
      // If exists in myTable use it, else add to hashtable
      if(myTable.ContainsKey(item.Key))
      {
         myObj = myTable[item.Key];
      }
      else
      {
         myObj = SomeIntensiveOperation();
         myTable.Add(item.Key, myObj); // Issue is here : breaks with exc during runtime
      }
      // Do something with myObj
      // some code here
  }
  </code></pre>
  
  <p>There must be some API, Property setting inside TPL library, that could handle this scenario. Is there?</p>