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 Static Constructor Deadlocking on Its Own Type

- 19.11.26 - ErcanOPAK

🔧 Fix a Static Constructor Deadlocking on Its Own Type

The CLR guarantees a type’s static constructor runs exactly once before the type is first used, enforcing this with an internal per-type lock held for the constructor’s entire duration. If that static constructor’s body — directly, or through a method it calls — triggers any code path that tries to access a static member of the SAME type again before the constructor finishes, the CLR detects it’s back on the same thread re-entering the same lock, and the result is either a wrapped `TypeInitializationException`, or, on a genuinely different thread blocked rather than re-entering, a true deadlock where that thread waits forever for initialization that’s itself waiting on something only that thread could finish.

🔎 The Problem

static class Config
{
    private static readonly Dictionary<string, string> _values = LoadValues();

    private static Dictionary<string, string> LoadValues()
    {
        // BuildDefault() reads Config.Fallback, a static field on this SAME
        // type, while the static constructor is still initializing it -
        // re-entrant access throws or deadlocks depending on the thread
        return BuildDefault(Config.Fallback);
    }

    public static readonly string Fallback = "default";
}

✅ Fix: Keep the Constructor Thin

  • Keep static constructors minimal and side-effect-free wherever possible — assign simple values, and defer any expensive or cross-cutting initialization to an explicit `Initialize()` method called deliberately at startup, not implicitly from the type-initialization path.
  • If a static constructor must call another method, trace every call it makes for any path that loops back to the SAME type’s static members, especially through a shared static field the constructor and the called method both touch — that self-reference is the direct cause of the re-entrancy.
  • For lazy, thread-safe static state that needs more control than a static constructor gives you — including the ability to retry after a failed first attempt, which a throwing static constructor permanently poisons — use `Lazy<T>` with an explicit thread-safety mode instead.

🚨 Why This Is Dangerous

  • A `TypeInitializationException` thrown from a re-entrant static constructor permanently marks that type as unusable for the rest of the process’s lifetime — every later attempt to use it, from completely unrelated code, throws the same cached exception again.

The CLR’s one-time guarantee for a static constructor is also a one-time chance – fail it once and the type stays broken for the rest of the process.

— C# Best Practice

Related posts:

.NET Core Connection Pooling — The Hidden Performance Giant

.NET Core Connection Pooling — The Hidden Performance Giant

C#: Use Async/Await for Asynchronous Programming

C#: Use Async/Await for Asynchronous Programming

C#: Fix a yield return Iterator Delaying Its Own Argument-Validation Exception Until the First Call ...

C#: Fix a yield return Iterator Delaying Its Own Argument-Validation Exception Until the First Call ...

Views: 2

Post navigation

C#: Fix a Source Generator Never Firing on an Incremental Build
Windows 11: Fix a Printer Queue Stuck After Waking From Sleep

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