Why does a .NET object with a finalizer survive at least one garbage collection longer than the same object without one, and what does that cost?
answer
- tracked while still alive
- a queue that is also a root
- one thread runs them
- promotion drags the graph along
- SuppressFinalize unregisters it
basics
~20 sWhen the .NET GC finds a finalizable object unreachable, it cannot free it: it queues the object for the finalizer thread, so the object and everything it references survive that collection and are promoted. Only a later collection reclaims them.
solid answer
~50 sThe runtime keeps track of every live object whose type overrides `Finalize` (a C# `~Type()` destructor). When a collection finds such an object unreachable, it moves it to the queue of objects ready for finalization, and that queue is a GC root, so the object **and its whole object graph** survive the collection and are promoted, from gen 0 to gen 1 or from gen 1 to gen 2. After the collection, the single **finalizer thread** runs the queued finalizers one by one. Only the next collection of the generation the object now lives in can reclaim it, and if it reached gen 2 that means a full collection. The costs: memory held longer, more promotion and gen 2 growth, and one thread that every finalizer waits on, so a slow or blocked finalizer makes memory climb. `GC.SuppressFinalize` removes the object from tracking, so the first collection that finds it unreachable reclaims it, like any other object.
code
csharp · 28 linesusing System.Runtime.CompilerServices;
var (shortRef, longRef) = Allocate(suppress: false);
GC.Collect(0);
Console.WriteLine($"after gen 0 GC: reachable={shortRef.IsAlive}, memory kept={longRef.IsAlive}, gen {GC.GetGeneration(longRef)}");
GC.WaitForPendingFinalizers();
Console.WriteLine($"finalizers run: {PriceSnapshot.Finalized}");
GC.Collect(1);
Console.WriteLine($"after gen 1 GC: memory kept={longRef.IsAlive}");
var (_, suppressed) = Allocate(suppress: true);
GC.Collect(0);
Console.WriteLine($"SuppressFinalize, after gen 0 GC: memory kept={suppressed.IsAlive}");
[MethodImpl(MethodImplOptions.NoInlining)]
static (WeakReference, WeakReference) Allocate(bool suppress)
{
var snapshot = new PriceSnapshot(new byte[1024]);
if (suppress) GC.SuppressFinalize(snapshot);
return (new WeakReference(snapshot), new WeakReference(snapshot, trackResurrection: true));
}
sealed class PriceSnapshot(byte[] data)
{
public static int Finalized;
public byte[] Data = data;
~PriceSnapshot() => Interlocked.Increment(ref Finalized);
}go deeper
Recall that a finalizer runs at an unpredictable time after an object becomes unreachable, and that the object's memory is not freed until after it has run.
Explain the queue, the extra survival, promotion of the whole object graph and the single finalizer thread, and what GC.SuppressFinalize changes.
Show how you would spot finalization pressure in production with FinalizationPendingCount or a blocked finalizer thread, and how you would remove it.
Set the team rule that finalizers are reserved for types that own native resources, with SafeHandle preferred, and justify it by its GC cost.
## What a finalizer is to the runtime A **finalizer** is an override of `Object.Finalize`, written in C# as a destructor (`~PriceSnapshot()`). The .NET runtime calls it before reclaiming the object's memory so the type can release something the GC does not manage, typically a native handle. To make that possible, the runtime keeps track of every live object of a finalizable type. That bookkeeping is where the extra survival comes from. ## The life of a finalizable object 1. **Allocation.** The object is created, and the runtime records that it has a finalizer to run. 2. **First collection that finds it unreachable.** A normal object would be reclaimed here. A finalizable one cannot be, because its finalizer has not run. The GC moves it to the **finalization queue** of objects ready to finalize. The .NET docs list the finalize queue among the GC's **roots**, next to static fields, stack locals, registers and GC handles, so the object is now reachable again, and so is everything it references. 3. **Survival and promotion.** Because it survived, the object is compacted and promoted with the other survivors: from gen 0 to gen 1, or from gen 1 to gen 2. Its referenced objects, for example a 1 KB buffer it holds, are promoted with it. 4. **Finalizer thread.** At the end of the collection the runtime signals the **finalizer thread**, one per process, which dequeues the objects one by one and runs each finalizer. 5. **Second collection.** Now the object is unreachable and no longer queued, so the next collection *of its new generation* reclaims it. If step 3 promoted it to gen 2, only a full collection can do that. The code example shows the sequence: after a gen 0 collection, an ordinary weak reference to the object is dead (the object is no longer reachable from code), a resurrection-tracking weak reference shows the memory is still held, now in generation 1, and only a later gen 1 collection reclaims it. ## What it costs - **Memory held longer.** The dispose-pattern guidelines say it directly: the object's memory, and all objects it refers to, is released at least one collection later. - **More promotion.** Objects that would have died in gen 0 move to gen 1 or gen 2. In a service that allocates finalizable objects per request, that inflates gen 2 and drives more full collections. - **One thread for everything.** Finalizers run serially on the finalizer thread. A finalizer that blocks on a lock, a network call or a single-threaded apartment holds up every later one, and their objects pile up. The .NET performance guide describes exactly this: a heap that does not shrink because the thread that services the finalizer queue cannot proceed. - **No timing guarantee.** A finalizer runs at some point after the object becomes unreachable, which depends on when its generation is next collected. | | No finalizer | Finalizer, not suppressed | `GC.SuppressFinalize` called | |---|---|---|---| | Collection that finds it unreachable | Reclaims it | Queues it, promotes it and its graph | Reclaims it | | Finalizer thread | Not involved | Runs `~Type()` | Not involved | | Memory freed | First collection | A later collection of the older generation | First collection | ## Detecting finalization pressure - `GC.GetGCMemoryInfo().FinalizationPendingCount` reports how many objects that collection saw as ready for finalization; a count that keeps climbing means the finalizer thread is falling behind. - The .NET performance guide's test, `GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();`, fixing a memory problem points to stalled finalizers. - Heap-dump tooling can list the finalization queue; that belongs with the diagnostics tools. ## Avoiding the cost - Do not add a finalizer "just in case"; only a type that directly owns an unmanaged resource needs one, and wrapping the handle in a `SafeHandle` usually removes the need. When to write one, and the `Dispose` pattern that calls `GC.SuppressFinalize`, belong with the material on disposal. - When a finalizable object has been cleaned up explicitly, `GC.SuppressFinalize(this)` clears its registration, so the first collection that finds it unreachable reclaims it directly. - Keep finalizers short and non-blocking, and keep finalizable objects small: move large buffers into separate objects that the finalizable one does not have to drag through promotion.
- What happens to memory if one finalizer in a .NET process blocks?Finalizers run one after another on the single finalizer thread, so a finalizer that blocks, for example waiting on a lock or a UI thread, stops every finalizer queued behind it. Those objects and everything they reference stay in memory, and the heap grows even though the code holds no references to them. `FinalizationPendingCount` in `GC.GetGCMemoryInfo()` keeps climbing in that state.
- Does GC.SuppressFinalize free an object's memory immediately?No. It only clears the object's finalization registration, so the next collection that finds it unreachable can reclaim it straight away, like an object without a finalizer. When that collection happens is still up to the GC. Calling it from `Dispose` is part of the dispose pattern, which belongs with the material on disposal.
- Why does it matter how much memory a finalizable object references?Everything reachable from a queued finalizable object survives the same collection and is promoted with it. A small finalizable wrapper that holds a large buffer drags that buffer into gen 1 or gen 2, where it can only be reclaimed by a costlier collection. Keeping the finalizable part small, with large data in separate objects, limits what survives.
- A finalizer runs as soon as the last reference to the object goes away.
- The GC runs finalizers inside the collection, so the memory is freed in that same collection.
- Finalizers run in parallel on thread pool threads.
- GC.SuppressFinalize frees the object's memory immediately.
- Adding a finalizer to every class is a harmless safety net.