title: Is AddOrUpdate thread safe in ConcurrentDictionary?
body: <p>I tried to use AddOrUpdate method in ConcurrentDictionary. </p>
  
  <p>From the "Remarks" section on this page <a href="https://msdn.microsoft.com/en-us/library/dd287191(v=vs.110).aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/dd287191(v=vs.110).aspx</a>. it says </p>
  
  <blockquote>
    <p>"However, delegates for these methods <strong>are called outside the locks</strong> to avoid the problems that can arise from executing unknown code under a lock. Therefore, the code executed by these delegates is not subject to the atomicity of the operation." </p>
  </blockquote>
  
  <p>So I am not sure whether it is thread safe. I have one case, if the key is not found, the value is 1, otherwise increase the value by 1.</p>
  
  <p>I wrote below function</p>
  
  <pre><code>    private static void AddOrUpdate(ConcurrentDictionary&lt;string, int&gt; map)
      {
          Random r = new Random();
          Thread.Sleep(r.Next(10));
          map.AddOrUpdate(Key, 1, (key, value) =&gt; value + 1);
      }
  
      public static void TestThreadSafe(ConcurrentDictionary&lt;string, int&gt; map)
      {
          Thread[] threads = new Thread[Size];
          for (int i = 0; i &lt; Size; ++i)
          {
              threads[i] = new Thread(() =&gt; AddOrUpdate(map));
          }
  
          foreach (var thread in threads)
          {
              thread.Start();
          }
      }
  </code></pre>
  
  <p>created about 300,000 threads and run them in parallel. The results are always 300,000. </p>
  
  <p>Is above method thread safe? When is AddOrUpdate not thread safe?</p>