Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Lazy<T> and the System.Threading.LazyThreadSafetyMode Enumeration

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

like image 574
Timothy Shields Avatar asked Dec 14 '12 00:12

Timothy Shields


People also ask

What is Lazy T?

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.

What is LazyThreadSafetyMode?

Native. 1.0. enum class LazyThreadSafetyMode. Specifies how a Lazy instance synchronizes initialization among multiple threads.

Is Lazy thread safe C#?

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.


1 Answers

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.

like image 86
Reed Copsey Avatar answered Sep 21 '22 04:09

Reed Copsey