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.
var config = new Lazy<string>(() => LoadConfig()); string text = config.Value; // LoadConfig runs here, once
Try it
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.
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
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
Valuetakes a volatile read after creation, so repeated access is cheap, but eachLazy<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
PublicationOnlyif you want retries, or build a newLazyafter a failure. PublicationOnlycan 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
Valuemay already hold, or you create a deadlock. - Async initialization. Use
Lazy<Task<T>>:new Lazy<Task<T>>(() => LoadAsync())andawait lazy.Value. The task is created once; remember that a faulted task stays faulted. - Static singletons are often simpler with a
static readonlyfield, since the CLR runs static initializers lazily and exactly once. UseLazy<T>when creation must depend on runtime values or be explicitly lazy. LazyInitializer.EnsureInitializedinitializes a field in place without a wrapper object; it may call the factory more than once under a race, likePublicationOnly.Lazy<T>and DI. RegisteringLazy<T>in a container only helps if the container resolves the inner service lazily as well.