Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Async and Concurrency

The Lazy<T> class

Reference for Lazy<T> in C#: create expensive values on first use, choose a thread-safety mode, handle exceptions and use LazyInitializer.

Lazy<T> delays creating a value until the first time you read its Value property. Later reads return the same instance. It is the standard way to defer expensive work (loading a configuration file, building a cache, opening a connection) that may never be needed.

By default Lazy<T> is thread-safe: if several threads ask for the value at the same moment, the factory runs once and every thread gets the same result. That also makes it a convenient way to build a thread-safe singleton.

C#
var config = new Lazy<string>(() => LoadConfig());
string text = config.Value;   // LoadConfig runs here, once

Try it

C# Create on first use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Thread-safety modes and exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public class Lazy<T>
{
    public Lazy();                                           // uses new T()
    public Lazy(Func<T> valueFactory);
    public Lazy(Func<T> valueFactory, bool isThreadSafe);
    public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode);
    public Lazy(T value);                                    // already created

    public T Value { get; }
    public bool IsValueCreated { get; }
}

public enum LazyThreadSafetyMode { None, PublicationOnly, ExecutionAndPublication }
Name Description
valueFactory Creates the value. Called at most once (or, in PublicationOnly, possibly several times concurrently).
mode None: no synchronization. PublicationOnly: several threads may run the factory, the first finished value wins. ExecutionAndPublication: one thread runs the factory, the others wait.
isThreadSafe true means ExecutionAndPublication, false means None.

Returns: Value returns the created instance; IsValueCreated tells whether Value has run successfully without forcing creation.

Errors: with ExecutionAndPublication and None, an exception from the factory is cached and rethrown on every access. Reading Value from inside the factory throws InvalidOperationException.

Usage notes

  • The factory is not the cheap part. Reading Value takes a volatile read after creation, so repeated access is cheap, but each Lazy<T> is an extra object plus a closure; do not wrap trivial values.
  • Cached exceptions surprise people: a transient failure (network down) sticks forever. Use PublicationOnly if you want retries, or build a new Lazy after a failure.
  • PublicationOnly can run the factory in parallel, so the factory must be side-effect free and any extra instances must be harmless to throw away (dispose them yourself).
  • Do not lock inside the factory on other locks that a thread calling Value may already hold, or you create a deadlock.
  • Async initialization. Use Lazy<Task<T>>: new Lazy<Task<T>>(() => LoadAsync()) and await lazy.Value. The task is created once; remember that a faulted task stays faulted.
  • Static singletons are often simpler with a static readonly field, since the CLR runs static initializers lazily and exactly once. Use Lazy<T> when creation must depend on runtime values or be explicitly lazy.
  • LazyInitializer.EnsureInitialized initializes a field in place without a wrapper object; it may call the factory more than once under a race, like PublicationOnly.
  • Lazy<T> and DI. Registering Lazy<T> in a container only helps if the container resolves the inner service lazily as well.