title: C# How do I update an element in BlockingCollection<T>?
body: <p>I have a <code>ConcurrentDictionaryWrapper</code> class that wraps <code>ConcurrentDictionary&lt;K,V&gt;</code> and implements the <code>IProducerConsumerCollection</code> interface so I can use it with a <code>BlockingCollection</code>. Producers will add values to the BlockingCollection with a key. The idea is that if the key exists, we replace the value in the underlying dictionary. My <code>ConcurrentDictionaryWrapper.TryAdd()</code> method is as follows:</p>
  
  <pre><code>public bool TryAdd(KeyValuePair&lt;TKey, TValue&gt; item)
  {
      _wrapped[item.Key] = item.Value
      return true;
  }
  </code></pre>
  
  <p>The problem I'm seeing is that if the value is replaced, the BlockingCollection will see this as an addition. </p>
  
  <pre><code>var wrapper = new ConcurrentDictionaryWrapper&lt;string, object&gt;();
  var bc = new BlockingCollection&lt;KeyValuePair&lt;string, object&gt;&gt;(wrapper);
  bc.TryAdd(new KeyValuePair&lt;string, object&gt;("key", new object()));
  bc.TryAdd(new KeyValuePair&lt;string, object&gt;("key", new object()));
  wrapper.Count; # returns 1
  bc.Count; # returns 2
  </code></pre>
  
  <p>I cannot return false in <code>TryAdd()</code> above because the BlockingCollection will raise an InvalidOperationException.</p>
  
  <p>Is there a way to achieve the behaviour I want? I want this to be as simple as possible but there doesn't seem to be a way to have this "AddOrUpdate" behaviour with a BlockingCollection by just implementing <code>IProducerConsumerCollection</code>. I want to avoid having to <code>TryTake()</code> before calling <code>TryAdd()</code> on the BlockingCollection &mdash; I would probably just use a standard lock around a Dictionary and synchronise the producers/consumers with <code>AutoResetEvent</code>.</p>