Scenario
Let's say we have:
var dictionary = new ConcurrentDictionary<string, Lazy<Heavy>>();
Instantiating Heavy
is very resource-consuming. Let's consider this code:
return dictionary.GetOrAdd("key", key =>
{
return new Lazy<Heavy>(() =>
{
return Instantiate();
});
}).Value;
The method Instantiate()
of course returns an instance of type Heavy
.
Question
For a given key, is it 100% guaranteed that the method Instantiate()
will be invoked at most once?
Sources
Some people claim that having multiple threads, we can only create multiple instances of Lazy<Heavy>
, which is very cheap. The actual method Instantiate()
will be invoked at most once.
- https://social.msdn.microsoft.com/Forums/en-US/e350f7d0-b860-482e-9b84-8dba12267d25/failure-of-lock-with-tpl?forum=parallelextensions
- http://reedcopsey.com/2011/01/16/concurrentdictionarytkeytvalue-used-with-lazyt/
I personally have an impression that this is false. What is the truth?