skip to content

What does C#'s Lazy<T> guarantee by default when many threads read Value, and how do LazyThreadSafetyMode and a throwing factory change that?

level: seniorimportance: should knowfreq 38%

answer

  1. the default mode takes a lock
  2. one factory run, one published value
  3. failures can be remembered
  4. a mode that races and retries

basics

~20 s

new Lazy<T>(factory) defaults to LazyThreadSafetyMode.ExecutionAndPublication: a lock lets one thread run the factory and all threads get its value. If that factory throws, Lazy caches the exception; PublicationOnly instead retries, but may run the factory on several threads.

solid answer

~40 s

`Lazy<T>` runs its factory on the first read of `Value`. The constructors without a mode use `LazyThreadSafetyMode.ExecutionAndPublication`: the implementation takes a `lock`, so one thread runs the factory, the others wait, and every thread sees the same instance. Two side effects follow. If the factory throws, the exception is **cached**: every later `Value` rethrows it and the factory never runs again. And a factory that reads `Value` on the same instance throws `InvalidOperationException`. `PublicationOnly` takes no lock: racing threads may each run the factory, the first to finish publishes its value, and a failure is not cached, so the next read retries. `None` has no thread-safety at all. For async initialisation, `Lazy<Task<T>>` caches the task itself, so a faulted task stays the value.

code

csharp · 24 lines
csharp
using System.Threading;

int calls = 0;
string Load()
{
    calls++;
    if (calls == 1) throw new IOException("config.json missing");
    return "{ \"limit\": 100 }";
}

var byDefault = new Lazy<string>(Load);
Probe("default", byDefault);
Probe("default", byDefault);

calls = 0;
var retrying = new Lazy<string>(Load, LazyThreadSafetyMode.PublicationOnly);
Probe("PublicationOnly", retrying);
Probe("PublicationOnly", retrying);

void Probe(string name, Lazy<string> lazy)
{
    try { Console.WriteLine($"{name}: {lazy.Value} (factory calls: {calls})"); }
    catch (IOException e) { Console.WriteLine($"{name}: {e.Message} (factory calls: {calls})"); }
}

go deeper

for a junior

Recall that Lazy<T> builds its value on the first read of Value and that the plain constructors are thread-safe by default.

for a middle

Explain the three LazyThreadSafetyMode values: who runs the factory, who waits, and what each does when the factory throws.

for a senior

Diagnose the production trap: a cached factory exception or a faulted Lazy<Task<T>> that keeps failing after the dependency recovers, and how to recreate the instance.

for a principal

Weigh lazy startup against eager initialisation: Lazy hides first-call latency and failure behind a property, which an eager health-checked start makes visible.

## What Lazy<T> is for `System.Lazy<T>` defers building an object until the first read of its `Value` property and then hands every later reader the same instance. A typical use is a configuration cache that is expensive to parse and is shared by every request thread: ```csharp private static readonly Lazy<Settings> s_settings = new(() => Settings.Load("config.json")); public static Settings Current => s_settings.Value; ``` The interesting part is what happens when many threads hit `Value` at the same moment, and when `Settings.Load` throws. Both are decided by **`LazyThreadSafetyMode`**. ## The default: ExecutionAndPublication The constructors that take no mode, `new Lazy<T>()` and `new Lazy<T>(Func<T>)`, pass **`LazyThreadSafetyMode.ExecutionAndPublication`**, and `new Lazy<T>(factory, isThreadSafe: true)` maps to the same mode. In the runtime source this mode wraps creation in a `lock`, and every thread that queued behind it re-checks whether the value was published before doing anything. The result: - the factory runs **once**; - other readers **block** until it finishes, then all see the same instance; - a factory that reads `Value` on the same `Lazy<T>` gets `InvalidOperationException` instead of recursing; - because the factory runs under a lock, the enum's own documentation warns that a factory which takes other locks internally can deadlock if not handled carefully. ## The three modes compared | Mode | Factory runs | Concurrent readers | Factory throws | |---|---|---|---| | `ExecutionAndPublication` (default) | once, under a lock | wait for the one run | exception cached, rethrown on every read | | `PublicationOnly` | possibly on every racing thread | each runs it; the first to finish publishes | not cached; the next read runs the factory again | | `None` | once if used from one thread | behaviour undefined | exception cached | `new Lazy<T>(factory, isThreadSafe: false)` selects `None`. Use it only when one thread is guaranteed to initialise the value. ## Exception caching in practice Exception caching is the behaviour that surprises people in production. Suppose the configuration file is briefly missing at startup: 1. The first read of `Value` runs the factory, which throws `IOException`. 2. In the default mode, `Lazy<T>` stores that exception; `IsValueCreated` stays `false`. 3. Every later read rethrows the **same** exception **without** calling the factory, even after the file appears. 4. The only way back is a new `Lazy<T>` instance, which usually means restarting the process when the field is `static readonly`. The example on this page runs both modes against a factory that fails once and then succeeds. With the default, both reads report `config.json missing` after a single factory call; with `PublicationOnly`, the second read calls the factory again and gets the value. Exception caching applies to the factory constructors; the runtime records the exception in the factory path. ## Lazy<T> and async initialisation When the factory is asynchronous, `Lazy<Task<T>>` is a common shape: the factory returns a `Task<T>` straight away, in the default mode the lock ensures only one task is started, and every caller awaits that task. The catch is that an `async` lambda **does not throw**; it returns a faulted task. That task is the cached value, so every `await` rethrows the failure and the factory is never called again, whichever mode you chose, because from `Lazy<T>`'s point of view creation succeeded. A run of this pattern reported one factory call and `IsValueCreated` `True` on both attempts. Retrying therefore means replacing the `Lazy<Task<T>>` (under a lock or with `Interlocked.CompareExchange`) when the stored task is faulted. ## Choosing a mode - **`ExecutionAndPublication`** when the factory is expensive or must not run twice, such as opening a connection pool, and a permanent failure is acceptable or handled by recreating the instance. - **`PublicationOnly`** when the factory is cheap, side-effect free, and a transient failure should be retried, accepting that it may run on several threads at once and the extra results are discarded. - **`None`** only for single-threaded initialisation where the lock's cost matters. - **Eager initialisation**, a `static readonly` field assigned directly or an object built at startup, when the cost is small: it fails at startup, where a health check sees it, instead of on the first request that happens to read `Value`. Using `Lazy<T>` values inside a concurrent dictionary to make a per-key factory run once is a separate pattern that belongs with thread-safe collections.

  • A Lazy<Task<Settings>> whose async factory failed keeps failing after the service recovers. Why, and how do you fix it?
    An `async` lambda returns a faulted `Task` instead of throwing, so `Lazy<T>` considers creation successful and caches that task in every mode. Each `await` rethrows the stored failure. Check whether the stored task is faulted and swap in a new `Lazy<Task<Settings>>`, guarded by a lock or `Interlocked.CompareExchange`.
  • What happens if a Lazy<T> factory reads Value on its own instance?
    In `ExecutionAndPublication` and `None` modes, it throws `InvalidOperationException`, because the factory has already been taken for the run in progress. `PublicationOnly` does not throw in that case, according to the enum's documentation.

  • Lazy<T> is not thread-safe unless you pass a mode explicitly.
  • After a factory exception, the next read of Value retries the factory.
  • PublicationOnly guarantees the factory runs exactly once.
  • A faulted Lazy<Task<T>> retries automatically on the next await.
  • Passing isThreadSafe: true to Lazy<T> selects PublicationOnly.