Skip to content

3.5 — Memory Leaks in Managed Code

← Roadmap · Section: 3. .NET Runtime and Platform Prev: 3.4 Garbage collection · Next: 3.6 Assemblies and NuGet

Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —


TL;DR

A memory leak in .NET is not forgetting to free memory — you cannot do that. It is accidentally keeping a reference to something you have finished with, so the garbage collector is not allowed to reclaim it.

  • The GC only frees what is unreachable. Anything still reachable from a root is kept, forever if necessary.
  • The big four causes: static collections, event handlers never unsubscribed, undisposed resources, and captured variables in long-lived closures.
  • The symptom is memory that climbs steadily and never comes back down, ending in an out-of-memory crash or a container restart.

Definitions

Term What it is What it means
Memory leak (managed) a bug Memory that is still reachable but will never be used again, so the GC cannot free it.
Memory leak (unmanaged) a different bug An OS resource — file handle, socket — never released because nothing called Dispose.
Reachable a property of an object The GC can get to it by following references from a root. Reachable objects are never freed.
Root a starting point Static fields, local variables of running methods, CPU registers. See 3.4.
Retention path a chain of references The route from a root to the leaked object. Finding this is how you fix a leak.
WeakReference<T> a class Holds a reference that does not stop the GC collecting the target.
Memory dump a file A snapshot of everything in the process's memory, for offline analysis.
dotnet-counters a CLI tool Shows live metrics — heap size, GC counts, thread-pool queue. First thing to run.
dotnet-dump a CLI tool Captures and analyses memory dumps. Finds what is holding an object alive.
dotnet-gcdump a CLI tool Captures just the object graph. Much smaller than a full dump and usually enough.

The concept

"You cannot leak memory in .NET" is wrong

People say this because the garbage collector frees things automatically. And it is true you cannot make the C-style mistake of forgetting to call free.

But the GC has one rule: free anything that is unreachable (3.4). It never asks "is this still needed?" — only "can this still be reached?"

So if you keep a reference to something you have finished with, the GC dutifully keeps it alive. Forever, if the reference lives in a static field.

That is a memory leak. The memory is not lost — it is being deliberately protected by your own code.

A picture: a warehouse where the rule is "throw away anything nobody has a claim ticket for". You cannot lose items. But if you keep handing out claim tickets and never collect them back, the warehouse fills up with things nobody actually wants — and the rule says every one of them must be kept.

Why it matters more in a web app

A desktop app gets restarted regularly. A web server is meant to run for weeks.

A leak of a few kilobytes per request sounds trivial. At 100 requests per second it is 35 gigabytes a day. In practice what happens is:

  1. Memory climbs steadily over hours.
  2. Gen 2 collections become more frequent and take longer, because the heap is huge.
  3. Latency gets worse as those pauses grow.
  4. Eventually the process hits its memory limit and is killed, or throws OutOfMemoryException.
  5. In Kubernetes the container restarts, memory resets, and the cycle begins again.

The classic signature is a sawtooth graph — memory rising steadily, dropping vertically at each restart. If you see that, you have a leak, not a tuning problem.


How it works

The simple version — the big four causes

1. Static collections that only grow ⚠️ the most common by far

public class OrderService
{
    // static = a GC root. Everything in here is reachable FOREVER.
    private static readonly List<Order> _processed = new();

    public void Process(Order order)
    {
        _processed.Add(order);      // nothing ever removes it
        // ...
    }
}

Every order ever processed stays in memory for the life of the process. And because Order holds a Customer, which holds an address, which holds..., you are retaining a whole object graph per order.

The fix is either to not keep it, or to use something with eviction:

// IMemoryCache has size limits and expiry. A raw dictionary does not.
_cache.Set(order.Id, order, TimeSpan.FromMinutes(10));

See 19.2.

2. Event handlers never unsubscribed ⚠️

public class OrderPage
{
    public OrderPage(OrderService longLivedService)
    {
        longLivedService.OrderCompleted += OnCompleted;   // subscribe
    }

    private void OnCompleted(object? s, EventArgs e) { }
}

Subscribing means the publisher stores a reference to the subscriber. The long-lived service now holds the short-lived page alive. Create a thousand pages and all thousand stay in memory, still receiving events.

The fix is to unsubscribe in Dispose — covered fully in 1.12, including the trap that you cannot unsubscribe a lambda unless you stored it in a variable.

3. Undisposed resources

var stream = File.OpenRead(path);    // never disposed

This is an unmanaged leak. The GC eventually frees the FileStream object's memory, but the operating system's file handle stays open until Dispose runs. Handles are a limited resource — run out and every subsequent file operation fails.

The fix is using — see 1.21.

4. Captured variables in long-lived closures

public class Registry
{
    private static readonly List<Action> _callbacks = new();

    public void Register(HugeObject data)
    {
        // The lambda captures 'data', so the closure object holds it.
        // The static list holds the closure. So 'data' lives forever.
        _callbacks.Add(() => Console.WriteLine(data.Name));
    }
}

A closure is a hidden object holding every captured variable (1.13). Store the lambda somewhere long-lived and you have stored everything it captured.

Worse, capturing any field of this captures the entire containing object, not just that field.

How it actually works — the ASP.NET Core specific ones

Injecting a scoped service into a singleton — the captive dependency problem:

public class CacheService                    // registered as a SINGLETON
{
    private readonly AppDbContext _db;       // SCOPED — meant to live one request

    public CacheService(AppDbContext db) => _db = db;
}

The singleton captures the first request's DbContext and holds it for the life of the application. That context's change tracker keeps every entity it has ever loaded, so it grows without limit. This is a leak and a correctness bug, since DbContext is not thread-safe. See 6.4.

Creating HttpClient per request:

using var client = new HttpClient();     // looks correct. Is not.

Disposing does not immediately release the underlying socket — it sits in TIME_WAIT for a couple of minutes. Under load you exhaust available ports. Use IHttpClientFactory — 19.10.

Long-lived DbContext in a background service:

protected override async Task ExecuteAsync(CancellationToken ct)
{
    using var scope = _factory.CreateScope();          // ONE scope for the whole loop
    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

    while (!ct.IsCancellationRequested)
    {
        var orders = await db.Orders.ToListAsync(ct);   // tracker grows every iteration
        await Task.Delay(TimeSpan.FromMinutes(1), ct);
    }
}

The scope must be created inside the loop, not outside — see 21.2.

The deeper detail — finding a leak in production

The method matters more than the tools, and this is a genuinely common interview scenario.

Step 1 — confirm it is actually a leak. Watch the heap size across several Gen 2 collections. A leak keeps climbing after a full collection. Normal load fluctuation drops back down.

dotnet-counters monitor --process-id <pid> --counters System.Runtime

Look at gen-2-gc-count and gc-heap-size. Rising heap with rising Gen 2 count means a leak.

Step 2 — capture the object graph.

dotnet-gcdump collect --process-id <pid>

Take two, several minutes apart. The difference between them is far more informative than either alone — it shows what is growing rather than what is merely large.

Step 3 — find the retention path. Open the dumps in Visual Studio or dotnet-dump, sort by object count, and find what grew. Then ask the crucial question: what is holding this alive? The chain from a root down to the leaked object is the retention path, and it points straight at the bug.

dotnet-dump analyze core_dump
> dumpheap -stat              # what is on the heap, by count and size
> gcroot <address>            # THE key command: what is keeping this alive

gcroot is the one to remember. It answers the only question that matters.

WeakReference<T> — occasionally the right tool

A weak reference lets you point at an object without stopping the GC collecting it:

private readonly WeakReference<ExpensiveThing> _cached = new(thing);

if (_cached.TryGetTarget(out var thing))
    Use(thing);            // still alive
else
    thing = Rebuild();     // was collected, rebuild it

Genuinely useful for caches where losing an entry is acceptable. Not a general fix for leaks — if you need the object, a weak reference just moves the bug. Reach for IMemoryCache first; it has proper eviction policies.


Code

The most common real leak, and its fix:

// LEAK — a singleton with an unbounded dictionary
public class PriceCache
{
    private readonly Dictionary<string, decimal> _prices = new();

    public decimal Get(string sku)
    {
        if (!_prices.TryGetValue(sku, out var price))
        {
            price = LookUp(sku);
            _prices[sku] = price;      // never removed, never expires
        }
        return price;
    }
}

Three problems, and being able to name all three is a strong answer:

  1. It only grows. New SKUs are added forever. This is the leak.
  2. It is not thread-safe. A Dictionary written from concurrent requests can corrupt — see 2.3.
  3. It is per-instance. Scale to three servers and you have three inconsistent caches.
// FIXED — bounded, expiring, thread-safe
public class PriceCache(IMemoryCache cache, IPriceApi api)
{
    public async Task<decimal> GetAsync(string sku, CancellationToken ct)
    {
        return await cache.GetOrCreateAsync(sku, async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15);
            entry.Size = 1;                       // counts against the cache size limit
            return await api.LookUpAsync(sku, ct);
        });
    }
}

Registered with a hard ceiling so it can never grow without limit:

builder.Services.AddMemoryCache(options => options.SizeLimit = 10_000);

That SizeLimit is the line that turns a potential leak into a bounded cache. Without it, IMemoryCache will also grow indefinitely — it only evicts on memory pressure, which may arrive too late.


Interview questions

Q: Can you have a memory leak in .NET?

Yes, though not in the C sense of forgetting to free memory. The garbage collector frees anything unreachable, but it never asks whether an object is still needed — only whether it can still be reached. So if you hold a reference to something you have finished with, the GC is obliged to keep it. A static collection that only grows, an event subscription never removed, or a lambda stored somewhere long-lived that captured a large object — all of those keep memory alive indefinitely. There is also the separate case of unmanaged resources like file handles, which the GC cannot release at all without Dispose.

Q: What are the most common causes?

Four, in roughly that order of frequency. Static collections that only ever get added to. Event handlers where the subscriber never unsubscribes, so a long-lived publisher pins a short-lived object. Undisposed resources holding operating system handles. And closures capturing large objects that are then stored somewhere long-lived — worth remembering that capturing any field implicitly captures the whole containing object. In ASP.NET Core specifically, injecting a scoped service like DbContext into a singleton is a very common one, because the singleton pins that context for the life of the app and its change tracker grows forever.

Q: How would you find a memory leak in production?

First confirm it is a leak rather than normal load, by watching whether the heap keeps growing after full Gen 2 collections — dotnet-counters shows heap size and Gen 2 count live. Then capture two dotnet-gcdump snapshots several minutes apart, because the difference tells you what is growing rather than just what is big. Then find the retention path: open the dump, sort by object count, identify what grew, and use gcroot to ask what is keeping it alive. That chain from root to object points at the bug. The mistake is jumping straight to a dump without first confirming there is actually a leak.

Q: What is a WeakReference and when would you use it?

A reference that does not prevent the garbage collector from collecting its target — you ask for the object with TryGetTarget and it may tell you it has gone. It suits caches where losing an entry is acceptable and rebuilding is cheaper than the memory cost of guaranteed retention. It is not a general fix for leaks though. If your code genuinely needs the object, making the reference weak just relocates the bug. For caching in ASP.NET Core I would reach for IMemoryCache with an explicit size limit first, because it gives you real eviction policies rather than depending on GC timing.


Traps ⚠️

  • "The GC means no leaks." The GC frees unreachable objects. Reachable-but-unwanted is the entire problem.
  • static is a GC root. Anything a static field points to lives for the whole process.
  • Capturing one field captures the whole object. A lambda using this.Name retains this.
  • Event subscribers are held by the publisher. Long-lived publisher plus short-lived subscriber equals a leak.
  • IMemoryCache without a SizeLimit can still grow indefinitely. It evicts on memory pressure, which may arrive too late.
  • Scoped services in singletons pin a request-lifetime object forever. See 6.4.
  • A DbContext held open accumulates every entity it has tracked. Use AsNoTracking for reads and short-lived contexts everywhere.
  • GC.Collect() will not fix a leak. The object is still reachable, which is exactly the problem.
  • One dump is much less useful than two. You need the delta to see what is growing.


Sources