System.Lazy<T> and the System.Threading.LazyThreadSafetyMode Enumeration
Asked Answered
R

1

5

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

Ress answered 14/12, 2012 at 0:30 Comment(0)
K
8

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.

Koby answered 14/12, 2012 at 0:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.