Using C#/.NET 4.0, a Lazy<T>
object can be declared as follows.
using System;
using System.Threading;
...
var factory = () => { return new object(); };
var lazy = new Lazy<object>(factory, LazyThreadSafetyMode.ExecutionAndPublication);
Other options from the LazyThreadSafetyMode
enumeration are PublicationOnly
and None
.
Why is there no ExecutionOnly
option?
The behavior in this case would be that the factory method is called at most once by a single thread, even if multiple threads try to get lazy.Value
. Once the factory method was completed and the single result was cached, many threads would be able to access lazy.Value simultaneously (i.e., no thread safety after the initial factory method).