title: How to add item to dictionary "Parallel loop safe"
body: <p>I have a Parallel.ForEach loop doing some treatment. But the first operation is to add a value in the dictionary if the key is not contained. I get an error when adding it, it says that the key is already in the dictionary. I guess that the key was added by a parallel process after the .Contains check of this thread, but before the add. Other than placing that line in a try-catch, is there another simple solution I can use to prevent that error?</p>
  
  <pre><code>Parallel.ForEach(branchFixes, b =&gt;
  {
    Parallel.ForEach(b.Value, t =&gt;
    {
      var team = t.Key;
      if (!resultTeamDict.ContainsKey(team))
      {
        resultTeamDict.Add(team, new Dictionary&lt;FixItem, Dictionary&lt;BranchInfo, bool&gt;&gt;());
      }
    });
  });
  </code></pre>