ConcurrentDictionary optimistic concurrent delete method

I was looking for a method in ConcurrentDictionary that allows me to delete a record by key, if and only if the value is equal to the one I specify, something like TryUpdate equivalent, but for deletion.

The only method that does this is this method:

ICollection<KeyValuePair<K, V>>.Remove(KeyValuePair<K, V> keyValuePair) 

This is an explicit implementation of the ICollection interface, in other words, I must first pass my ConcurrentDictionary to ICollection so that I can call Remove.

Delete does exactly what I want, and that casting doesn't matter much, also the source code shows that it calls the private TryRemovalInternal method with bool matchValue = true, so everything looks beautiful and clean.

What bothers me a bit is the fact that it is not documented as an optimistic parallel Remove ConcurrentDictionary method, so http://msdn.microsoft.com/en-us/library/dd287153.aspx just duplicates the ICollection pattern, and How to add and remove items from ConcurrentDictionary also does not mention this method.

Does anyone know if this can go, or is there some other method that I am missing?

+7
source share
2 answers

Although this is not an official document, this MSDN blog post may be helpful. The essence of this article: discarding ICollection and calling its Remove method, as described in the question, is the way to go.

Here is a snippet from the blog post above that takes it to TryRemove extension TryRemove :

 public static bool TryRemove<TKey, TValue>( this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, TValue value) { if (dictionary == null) throw new ArgumentNullException("dictionary"); return ((ICollection<KeyValuePair<TKey, TValue>>)dictionary).Remove( new KeyValuePair<TKey, TValue>(key, value)); } 
+4
source

If you don't need all the calls to ConcurrentDictionary, you can simply declare your type as an IDictionary.

 public class ClassThatNeedsDictionary { private readonly IDictionary<string, string> storage; public ClassThatNeedsDictionary() { storage = new ConcurrentDictionary<string, string>(); } public void TheMethod() { //still thread-safe this.storage.Add("key", "value"); this.storage.Remove("key"); } } 

I find this useful in situations where you only need to add and remove, but still want to do a stream iteration.

0
source

All Articles