Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix a Lazy Initializer Running Twice Under Thread Contention

- 17.11.26 - ErcanOPAK

đź”§ 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.ExecutionAndPublication whenever 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 PublicationOnly specifically 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.

— C# Best Practice

Related posts:

Converting a List to a comma separated string in C#

Converting a List to a comma separated string in C#

C# Async “Hangs Forever” Problem — Why Task Never Completes Under Load

C# Async “Hangs Forever” Problem — Why Task Never Completes Under Load

C#: Expression Trees ile Runtime Query OluĹźturma

C#: Expression Trees ile Runtime Query OluĹźturma

Views: 5

Post navigation

JavaScript: Fix a WeakMap Losing Entries After a Structured Clone
Ajax: Fix an AbortController Signal Not Cancelling a Pending Fetch

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,059)
  • Get the User Name and Domain Name from an Email Address in SQL (983)
  • How to add default value for Entity Framework migrations for DateTime and Bool (981)
  • Get the First and Last Word from a String or Sentence in SQL (861)
  • How to select distinct rows in a datatable in C# (856)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (658)
  • Add Constraint to SQL Table to ensure email contains @ (613)
  • Average of all values in a column that are not zero in SQL (571)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (549)
  • Find numbers with more than two decimal places in SQL (477)

Recent Posts

  • Visual Studio: Fix Quick Actions Hiding Behind a Stale Squiggle
  • Photoshop: Fix a Smart Filter Resetting After You Relink It
  • Ajax: Fix a Cancelled Request Still Updating Stale UI State
  • C#: Fix a Span Captured by a Lambda Throwing at Runtime
  • The AI Prompt That Converts a REST Endpoint Into a Typed SDK
  • Git: Fix a Worktree Locking a Branch Needed Somewhere Else
  • Asp.Net Core: Fix a Background Service Leaking Scoped Dependencies
  • SQL Server: Fix a Columnstore Index Fragmenting After Bulk Deletes
  • Docker: Fix a Container Losing Logs After a Restart Policy
  • Asp.Net Core: Fix Output Caching Serving a Stale Authorized Page

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,059)
  • Get the User Name and Domain Name from an Email Address in SQL (983)
  • How to add default value for Entity Framework migrations for DateTime and Bool (981)
  • Get the First and Last Word from a String or Sentence in SQL (861)
  • How to select distinct rows in a datatable in C# (856)

Recent Posts

  • Visual Studio: Fix Quick Actions Hiding Behind a Stale Squiggle
  • Photoshop: Fix a Smart Filter Resetting After You Relink It
  • Ajax: Fix a Cancelled Request Still Updating Stale UI State
  • C#: Fix a Span Captured by a Lambda Throwing at Runtime
  • The AI Prompt That Converts a REST Endpoint Into a Typed SDK

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com