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).
The Lazy<T> object ensures that all threads use the same instance of the lazily initialized object and discards the instances that are not used.
Native. 1.0. enum class LazyThreadSafetyMode. Specifies how a Lazy instance synchronizes initialization among multiple threads.
By default, Lazy<T> objects are thread-safe. That is, if the constructor does not specify the kind of thread safety, the Lazy<T> objects it creates are thread-safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With