0

In a C# Concurrent Dictionary, specifically the signature . . .

public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)

. . . I know it is possible for valueFactory to be called multiple times. What happens to the multiple return values though? Is it guaranteed that only one result will ever be mapped in the dictionary, or is there any possibility that there is a window where other threads can see different values in the dictionary?

Chris Schmich
  • 29,128
  • 5
  • 77
  • 94
Chuu
  • 4,301
  • 2
  • 28
  • 54

1 Answers1

1

Looking in reflector the valueFactory is only executed because of an internal method that accepts a value and not a delegate. After that, as I undestand it, it's as if you've called the reguler overload that accepts a value and not a delegate.

so basically, the value from the delegate is ignored, and not mapped to the dictionary. The value in the dictionary is always the same, and as such threads always see the same value (because, using GetOrAdd only one value is ever mapped).

Obviously if you change the value using AddOrUpdate values will get updated.

Linkgoron
  • 4,866
  • 2
  • 26
  • 26