đź”§ C#: Fix a Lazy Initializer Running Twice Under Thread Contention
Lazy<T> constructed with LazyThreadSafetyMode.PublicationOnly explicitly allows its factory delegate to run more than once under thread contention — multiple threads racing to initialize are each allowed to execute the factory concurrently, and whichever result finishes first is the one that gets published, with every other thread’s result silently discarded. That’s a deliberate trade-off to avoid a failed initialization permanently poisoning future attempts, but it’s a dangerous default to reach for when the factory has any side effect — an API call, a file write — because ‘ran twice, discarded one result’ is exactly as destructive as it sounds for anything that isn’t a pure computation.
🔎 The Problem
private static readonly Lazy<Connection> _connection = new Lazy<Connection>(
() => OpenConnectionAndRegisterWithExternalService(),
LazyThreadSafetyMode.PublicationOnly
);
// Two threads race to access _connection.Value concurrently:
// BOTH may call OpenConnectionAndRegisterWithExternalService(),
// registering with the external service TWICE - only one
// resulting Connection object becomes _connection.Value, but
// the other registration already happened and can't be undone
âś… Fix: Reserve PublicationOnly for Side-Effect-Free Factories
- Use the default
LazyThreadSafetyMode.ExecutionAndPublicationwhenever the factory has any observable side effect — it guarantees the factory runs exactly once, at the cost of other threads blocking briefly until that one run completes. - Reserve
PublicationOnlyspecifically for pure, idempotent factories where running twice and discarding one result is genuinely harmless — a pure computation, not anything that calls out to an external system or mutates shared state. - If you inherited code using
PublicationOnly, check the factory for side effects specifically before assuming the mode choice was deliberate — it’s an easy setting to copy from an example without registering what it actually permits.
🚨 Why This Is Dangerous
- Registering a client twice with a third-party billing or metering API because a ‘thread-safe’ Lazy initializer was configured with PublicationOnly specifically to avoid blocking, with nobody realizing that setting explicitly allows the side-effecting factory to run more than once by design.
PublicationOnly doesn’t mean the factory runs once safely — it means it’s allowed to run more than once and still call itself safe.
