The Analogy: The Overnight Cleaners
An office has a cleaning crew that comes through when the desks go quiet. They have one rule for deciding what is rubbish: if nobody is holding it and nobody's desk has a note pointing at it, it goes. They do not check whether you meant to keep the crate in the corner, and they do not care how expensive it was. Reachable means keep; unreachable means gone.
The crew is also smart about where they spend their time. They have learned that almost everything discarded in a single day was brought in that same day — the coffee cups, the printouts, the sticky notes — while the filing cabinets that survived last month will probably survive this one too. So they sweep the new stuff constantly and cheaply, and only do a full warehouse audit occasionally, because auditing the whole building is slow.
That is the generational garbage collector, and its rule is the important half. The GC does not free objects you are finished with; it frees objects nothing can reach. A "memory leak" in C# is never the collector failing — it is always something, somewhere, still holding a note: a static list, an event you never unsubscribed from, a timer you never stopped, a closure that captured more than you thought.
The crew also has a blind spot. They handle the warehouse's own crates perfectly, but they know nothing about the things outside it — the file the building has open, the socket connected to another office, the native handle from a machine in the basement. Those need someone to close them explicitly and on time, which is what IDisposable exists for, and why a finalizer is a safety net rather than a plan.
Syntax or Core Structure
using System;
class Resource : IDisposable
{
private readonly string name;
private bool disposed;
public Resource(string name)
{
this.name = name;
Console.WriteLine("open " + name);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this); // the safety net is no longer needed
}
protected virtual void Dispose(bool disposing)
{
if (disposed) return; // Dispose must be safe to call twice
if (disposing) Console.WriteLine("close " + name);
disposed = true;
}
~Resource() => Dispose(false); // runs only if Dispose was forgotten
}
class Program
{
static void Main()
{
using (Resource outer = new Resource("outer"))
using (Resource inner = new Resource("inner"))
{
Console.WriteLine("working");
} // disposed in reverse order
Resource twice = new Resource("twice");
twice.Dispose();
twice.Dispose(); // second call is a no-op
using Resource scoped = new Resource("scoped"); // disposed at end of Main
Console.WriteLine("end of Main");
}
}
Output:
open outer
open inner
working
close inner
close outer
open twice
close twice
open scoped
end of Main
close scoped
Notice that this output says nothing about the garbage collector, and that is the point: every "close" line is caused by Dispose, not by collection. Disposal is deterministic — you know exactly when it happens — whereas collection is not, and code that needs a resource released at a particular moment must not rely on the crew arriving.
The reverse ordering of close inner and close outer follows from the nesting: using blocks unwind innermost-first, which is what you want when the inner resource was built from the outer one. The using declaration on scoped is the same thing without the braces — it disposes at the end of the enclosing scope, which is why close scoped prints after end of Main.
The two Dispose calls on twice produce one close. That idempotence is part of the contract: Dispose may be called any number of times and must never throw on the later ones, because using blocks, DI containers, and defensive callers all call it independently.
GC.SuppressFinalize(this) is the line beginners omit. Without it, an object with a finalizer is put on the finalization queue at allocation and needs two collections to actually die: one to notice it is unreachable and queue it for finalization, another to free it after the finalizer thread has run. Suppressing that when Dispose has already done the work is free performance.
Technical Depth: How the Crew Actually Works
Allocation is almost free: the heap keeps an allocation pointer and a new object is a bounds check plus a pointer bump. The cost is all in collection.
| Generation | Holds | Collected | Typical cost |
|---|---|---|---|
| Gen 0 | Freshly allocated objects | Very often | Sub-millisecond |
| Gen 1 | Gen 0 survivors; a buffer | Often | Around a millisecond |
| Gen 2 | Long-lived objects | Rarely | Tens to hundreds of ms |
| LOH | Allocations 85,000 bytes and larger | With gen 2 | Not compacted by default |
| POH | Pinned objects (.NET 5+) | With gen 2 | Keeps pins out of the way |
A collection has three phases: mark (walk every root — thread stacks, statics, GC handles — and flag everything reachable), sweep (the unmarked space becomes free), and compact (slide survivors together so allocation stays a pointer bump). Survivors are promoted to the next generation, which is why an object that lives through a couple of gen-0 collections becomes expensive to collect later.
Why gen 0 stays cheap
Collecting gen 0 alone would be wrong if an old object held a reference to a new one — the collector would have to scan gen 2 to find out. Instead the runtime installs a write barrier: every store of a reference into an object's field records the region in a card table, so a gen-0 collection only rescans the few dirty cards rather than the whole old heap. This is also a small tax on every reference assignment, and one more reason value types in arrays are fast: no references, no barriers, no cards.
Workstation, server, and background
<ServerGarbageCollection>true</ServerGarbageCollection>
<ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
Workstation GC uses one heap and favours short pauses; server GC uses a heap and a dedicated thread per core and favours throughput, at the cost of memory. Background (concurrent) GC does most of the gen-2 mark phase while your threads keep running, shrinking the stop-the-world window. ASP.NET Core defaults to server GC; a small container may well be better off with workstation, and .NET 9's DATAS adapts heap count dynamically for exactly that case.
The large object heap
Anything 85,000 bytes or larger — a big byte[], a large array of doubles — goes straight to the LOH, is collected only with gen 2, and is not compacted by default. Repeatedly allocating and freeing large buffers therefore fragments memory in a way the collector will not tidy up. ArrayPool<T>.Shared exists precisely to avoid this: rent a buffer, use it, return it.
Where managed leaks actually come from
| Cause | Why it holds on | Fix |
|---|---|---|
static collection | Statics are roots and live forever | Bound the size, or evict |
| Event subscription | The publisher holds the subscriber | Unsubscribe, or use a weak pattern |
Timer / CancellationTokenSource | The runtime holds the callback | Dispose the timer, unregister the callback |
| Captured closure | Captures the whole enclosing scope | Copy out only the values you need |
ThreadLocal / AsyncLocal | Lives as long as the thread or flow | Dispose, or clear on completion |
Undisposed HttpResponseMessage etc. | Holds buffers and connections | using, or a pooled client |
Things not to do
GC.Collect() in production code is almost always wrong: it forces a full collection, promotes surviving garbage, and hides the real problem. GC.WaitForPendingFinalizers() can deadlock if a finalizer touches something the calling thread holds. GCSettings.LatencyMode and TryStartNoGCRegion exist for genuinely latency-critical windows, and both need measurement to justify.
Real World Example: The Subscription That Never Died
A dashboard app opens and closes views all day, and its memory climbs steadily until it is restarted. Nothing is obviously wrong, and forcing a collection changes nothing — because the objects are still reachable.
using System;
using System.Collections.Generic;
class Ticker
{
public event EventHandler<int>? Tick;
// The invocation list is exactly the set of objects this ticker holds.
public int SubscriberCount => Tick?.GetInvocationList().Length ?? 0;
public void Publish(int value) => Tick?.Invoke(this, value);
}
class Dashboard : IDisposable
{
private readonly Ticker ticker;
private readonly string name;
public int Last { get; private set; }
public Dashboard(string name, Ticker ticker)
{
this.name = name;
this.ticker = ticker;
ticker.Tick += OnTick; // the ticker now points at us
}
private void OnTick(object? sender, int value) => Last = value;
public void Dispose() => ticker.Tick -= OnTick; // let go of the note
}
class Program
{
static void Main()
{
Ticker ticker = new Ticker();
Console.WriteLine("subscribers at start: " + ticker.SubscriberCount);
List<Dashboard> views = new List<Dashboard>();
for (int i = 1; i <= 3; i++) views.Add(new Dashboard("leak-" + i, ticker));
Console.WriteLine("after 3 leaky views: " + ticker.SubscriberCount);
views.Clear(); // we dropped our references...
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("after Clear and GC: " + ticker.SubscriberCount);
using (Dashboard tidy = new Dashboard("tidy", ticker))
{
Console.WriteLine("with a tidy view: " + ticker.SubscriberCount);
}
Console.WriteLine("after tidy disposed: " + ticker.SubscriberCount);
}
}
Output:
subscribers at start: 0
after 3 leaky views: 3
after Clear and GC: 3
with a tidy view: 4
after tidy disposed: 3
The third line is the whole diagnosis. views.Clear() released the list's references, and GC.Collect() gave the crew an explicit invitation — and the count is still 3, because the direction of the reference is the opposite of the direction of the intuition. The dashboards subscribed to the ticker, so the ticker holds delegates whose Target is each dashboard. The ticker is alive, therefore the delegates are alive, therefore the dashboards are alive, along with every field they hold: their cached data, their child controls, their buffers.
That is why "the GC is not collecting my objects" is essentially never true. SubscriberCount is measured from the event's invocation list rather than from any GC statistic, which is what makes this output stable — and it is also the technique to use in a real investigation. If you can count the things a long-lived object still points at, you can find the leak without a memory profiler.
The tidy view shows the fix, and shows how small it is: ticker.Tick -= OnTick in Dispose. Delegate removal works here because two delegates are equal when they wrap the same method on the same target, so the -= finds the exact entry that += added. This is precisely why subscribing with a lambda — ticker.Tick += (s, v) => Last = v; — is a trap: you have no reference to remove later, and the subscription becomes permanent.
In production the same shape appears wherever something long-lived points at something short-lived: a singleton service raising events consumed by scoped objects, a static cache of view models, an IChangeToken callback that is never unregistered. The rule is symmetric and easy to audit — whoever writes += owns the matching -=, and if the subscriber's lifetime is shorter than the publisher's, that pairing belongs in Dispose.
Common Mistakes
- Calling
GC.Collect()to fix a memory problem. It forces an expensive full collection, promotes live garbage to gen 2, and cannot free anything that is still reachable. - Assuming unreferenced means collected. An event subscription, a static list, or a running timer keeps the object rooted. Follow the references before blaming the collector.
- Subscribing with a lambda you cannot unsubscribe. Store the handler in a field, or use a method group, so
-=has something to match. - Writing a finalizer for managed-only state. It delays collection to two passes, runs on a separate thread in an unpredictable order, and can resurrect objects. Only native handles justify one.
- Forgetting
GC.SuppressFinalizeinDispose. The finalizer then runs anyway, paying the two-collection cost you had already avoided. - Letting
Disposethrow on a second call. Callers,usingblocks and DI containers all dispose independently; the method must be idempotent. - Churning large buffers. Anything 85,000 bytes or more lands on the uncompacted LOH, so allocate-and-drop cycles fragment memory. Rent from
ArrayPool<T>.Sharedinstead. - Treating an unbounded static cache as free. Statics are GC roots, so every entry lives until the process ends. Give caches a size limit and an eviction policy.
Best Practices
- Implement
IDisposablefor anything holding a file, socket, native handle, or another disposable, and wrap it inusingat every call site. - Prefer
SafeHandleover a hand-written finalizer; it already gets the critical-finalization and double-free details right. - Pair every
+=with a-=, and put the unsubscribe inDisposewhenever the subscriber is shorter-lived than the publisher. - Reduce allocation rate rather than tuning the collector: reuse buffers, avoid boxing, and use
Span<T>for slicing instead of copying. - Use
ArrayPool<T>orMemoryPool<T>for buffers of a kilobyte or more, and always return what you rent in afinally. - Bound every cache — a size limit, a sliding expiry, or
WeakReference<T>values — so it cannot become a leak. - Implement
IAsyncDisposablewhen cleanup needs I/O, and useawait usingso the flush is awaited rather than blocked on. - Diagnose with evidence: allocation profiling,
dotnet-countersfor gen counts and heap size, and a heap dump to find who holds the reference.
Practice Exercises
- Reproduce the leak at scale. Create ten thousand
Dashboardinstances against one ticker without disposing them, printGC.GetTotalMemory(true)before and after, then repeat with disposal. Explain the difference in bytes. - Write a
WeakEventManagerthat stores subscribers inWeakReference<object>and prunes dead entries on each publish. Prove with a test that a subscriber becomes collectable without an explicit unsubscribe, and state the drawback of this design. - Implement the full dispose pattern on a class that owns both a
FileStreamand a managedList<string>. IncludeDispose(bool),GC.SuppressFinalize, anObjectDisposedExceptionguard on every public member, and a test that callsDisposethree times. - Allocate a 100,000-byte array in a loop one thousand times and record
GC.CollectionCount(2). Then rewrite it withArrayPool<byte>.Shared.Rent/Returnand compare both the gen-2 count and the elapsed time.