Thursday, February 3, 2011

ConcurrentDictionary Extensions

With the new .NET Framework 4, Microsoft has introduced new concurrent collection classes in the System.Collection.Concurrent namespace. I had written a thread safe dictionary (that used locks), which I could replace with the new ConcurrentDictionary. However, my implementation had some useful methods which I did not want to lose, so I wrote these extension methods:
  •  bool TryRemove(TKey key)
    This method can be used when you don't care about the value that is removed.
  • TValue GetOrDefault(TKey key)
    Useful when you want to use the types default value if the key is not in the dictionary.
  •  TValue AddOrUpdate(TKey key, TValue value)
    When the value is already known and you don't want to use the Func parameter.
  • TValue GetOrAdd(TKey key, Func<TValue> valueFactory)
    When the valueFactory functions execution does not depend on the key.
  • int RemoveConditional(Predicate<TValue> condition)
    This method removes all key value pairs where the value meets a condition and returns the count of removed items. Warning: This method is not thread-safe. If one thread changes the value between the check of the condition and removal, the key is still removed.
The download contains one class with the extension methods and another with some tests.

Click here to download

1 comment:

  1. Congratulation for the new blog ... already subscribed to the rss feed :-)

    Next-Step: Publish the code on GitHub :-)