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 ConditionalWeakTable Entry Vanishing Too Soon

- 16.11.26 - ErcanOPAK

🔧 C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon

ConditionalWeakTable<TKey, TValue> ties an entry’s lifetime to its key object being reachable – the moment nothing else in the application holds a strong reference to the key, the garbage collector is free to collect it and the table drops that entry, value included, even if the value itself is referenced elsewhere. A common version of this bug keys the table on an object that’s itself short-lived – a request-scoped DTO, or a wrapper created fresh just to do the lookup – so the entry can disappear between one method call and the next, not because of a race, but simply because nothing held the key object alive in between.

🔎 The Problem

static readonly ConditionalWeakTable<object, Metadata> _table = new();

Metadata GetMetadata(SomeDto dto)
{
    var wrapper = new LookupKey(dto.Id); // short-lived, created fresh
    _table.TryGetValue(wrapper, out var meta); // wrapper is already
    return meta;                                // eligible for GC here
}

✅ Fix: Key on the Object That Actually Lives as Long as the Data Should

  • Key the table on the actual long-lived object the extra data conceptually belongs to, and keep a reference to that same key object anywhere the lookup needs to succeed later – not on a short-lived wrapper or DTO created fresh for each call.
  • If the value genuinely needs to outlive the key becoming unreachable, a ConditionalWeakTable<TKey, TValue> is the wrong tool entirely; use a regular dictionary with an explicit removal strategy instead of forcing weak-table semantics to do a strong table’s job.
  • Add a test that explicitly forces a garbage collection between storing and retrieving a value, since a test that stores and immediately reads back in the same method holds the key alive on the stack the whole time and will never catch this bug.

🚨 Why This Is Dangerous

  • A cache or metadata table that “mostly works” and occasionally returns a miss for an object you’re certain you stored data for is easy to misdiagnose as a logic bug, when the real cause is that the key was already collected before the lookup ever ran.

A ConditionalWeakTable only remembers for as long as something else already remembers the key – it was never meant to be the thing keeping an object alive.

— C# Best Practice

Related posts:

C#: Use Async/Await for Asynchronous Programming

C#: Use Async/Await for Asynchronous Programming

C#: Fix a Tuple Deconstruction That Silently Swaps Two Values of the Same Type

C#: Fix a Tuple Deconstruction That Silently Swaps Two Values of the Same Type

C# DateTime Bugs Appear Across Servers

C# DateTime Bugs Appear Across Servers

Views: 4

Post navigation

Docker: Fix a Stale COPY Layer After Editing .dockerignore

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,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (976)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (852)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (607)
  • Average of all values in a column that are not zero in SQL (569)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (546)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

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

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

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