title: Is it safe to r/w dictionary entries in a Parallel.ForEach in c#
body: <p>I have a dictionary which I would like to modify it's values in a foreach loop, however, since my application is time critical, I'm trying to avoid all unnecessary locking overheads.</p>
  
  <pre><code>var loopData = new Dictionary&lt;int, List&lt;string&gt;&gt;();
  var results = new Dictionary&lt;int, List&lt;string&gt;&gt;();
  
  /// loopData and results are both initialized
  /// with same set of keys.
  
  Parallel.ForEach(loopData, data =&gt;
      {
          var list = data.Value;
          /// manipulate list here
  
          /// Is this safe?
          results[data.Key] = list;
      });
  </code></pre>
  
  <p>Is the marked command safe to do? i.e., read/write to different key-value pairs of a dictionary without locking.</p>
  
  <p><strong>Note 1:</strong> I'm aware of concurrent collections namespace and all it's magnificent collections. Also I know that I can simply <code>lock</code> the highlighted command to ensure it's safety. As afore mentioned, my target is avoid <em>unnecessary</em> overheads as much as possible. </p>
  
  <p><strong>Note 2:</strong> a similar question is asked <a href="https://stackoverflow.com/questions/5605422/is-this-use-of-parallel-foreach-thread-safe">at this link</a>. In that question the items of the container are modified inside the <code>Parallel.ForEach</code> loop. Whereas, here we are not modifying the key-value pairs, therefore the container is intact, only the data being pointed is changed. This makes it different from aforementioned question.</p>
  
  <p><strong>Update</strong></p>
  
  <ol>
  <li>This code works fine with no locking, but I <em>must</em> be sure.</li>
  <li>Eventhough the <code>ConcurrentDictionary</code> would add least possible overhead, I would like to avoid it if this is safe.</li>
  </ol>