Question

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).

Was it helpful?

Solution

The behavior you're describing is effectively LazyThreadSafetyMode.ExecutionAndPublication. This allows multiple threads to access the Value, but only a single thread to ever run the initialization method.

This enumeration is solely for determining how the creation occurs - you can always access Value from multiple threads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top