title: Atomic AddOrUpdate for a C# Dictionary
body: <p>Suppose the following code:</p>
  <pre><code>if (myDictionary.ContainsKey(aKey))
      myDictionary[aKey] = aValue;
  else
      myDictionary.Add(aKey, aValue);
  </code></pre>
  <p>This code accesses the dictionary two times, once for determining whether <code>aKey</code> exist, another time for updating (if exists) or adding (if does not exist). I guess the performance of this method is &quot;acceptable&quot; when this code is executed only a few times. However, in my application similar code is executed roughly 500K times. I profiled my code, and it shows 80% of CPU time spent on this section (see the following figure), so this motivates an improvement.</p>
  <p><a href="https://i.stack.imgur.com/2uQx7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2uQx7.jpg" alt="" /></a>
  Note that, the dictionary is <code>lambdas</code>.</p>
  <p><strong>First workaround</strong> is simply:</p>
  <pre><code>myDictionary[aKey] = aValue;
  </code></pre>
  <p>If <code>aKey</code> exist it's value is replaced with <code>aValue</code>; if does not exist, a <code>KeyValuePair</code> with <code>aKey</code> as key and <code>aValue</code> as value is added to <code>myDictionary</code>. However, this method has two drawbacks:</p>
  <p><em>First</em>, you don't know if <code>aKey</code> exist or not that prevents you from additional logics. For instance, you can not rewrite following code based on this workaround:</p>
  <pre><code>int addCounter = 0, updateCounter = 0;
  if (myDictionary.ContainsKey(aKey))
  {
      myDictionary[aKey] = aValue;
      addCounter++;
  }
  else
  {
      myDictionary.Add(aKey, aValue);
      updateCounter++;
  }
  </code></pre>
  <p><em>Second</em>, the update can not be a function of the old value. For instance, you can not do a logic similar to:</p>
  <pre><code>if (myDictionary.ContainsKey(aKey))    
      myDictionary[aKey] = (myDictionary[aKey] * 2) + aValue;    
  else    
      myDictionary.Add(aKey, aValue);
  </code></pre>
  <p>The <strong>second workaround</strong> is to use <code>ConcurrentDictionary</code>. It's clear that by using  <code>delegates</code> we can solve the <em>second</em> aforementioned issue; however, still, it is not clear to me how we can address the <em>first</em> issue.</p>
  <p>Just to remind you, my concern is to speed up. Given that there is only one thread using this procedure, I don't think the penalty of concurrency (with locks) for only one thread is worth using <code>ConcurrentDictionary</code>.</p>
  <p>Am I missing a point? does anyone have a better suggestion?</p>