🔧 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.
