Search code examples
c#.netmultithreadingparallel-processingconcurrentdictionary

Is ConcurrentDictionary.GetOrAdd() guaranteed to invoke valueFactoryMethod only once per key?


Problem: I need to implement object cache. The cache need to be thread-safe and need to populate values on demand(lazy loading). The values are retrieved via web service by Key(slow operation). So I've decided to use ConcurrentDictionary and its GetOrAdd() method that has a value factory method supposing that the operation is atomic and synchronized. Unfortunately I found the following statement in the MSDN article: How to: Add and Remove Items from a ConcurrentDictionary:

Also, although all methods of ConcurrentDictionary are thread-safe, not all methods are atomic, specifically GetOrAdd and AddOrUpdate. The user delegate that is passed to these methods is invoked outside of the dictionary's internal lock.

Well that's unfortunate but still doesn't answer my answer completely.

Question: Is value factory invoked only once per key? In my specific case: Is it possible that multiple threads that are looking for the same key spawning multiple request to the web service for the same value?


Solution

  • Is value factory invoked only once per key?

    No, it isn't. The docs say:

    If you call GetOrAdd simultaneously on different threads, valueFactory may be invoked multiple times, but its key/value pair might not be added to the dictionary for every call.