الانتقال إلى المحتوى
.NETPerformance· 7 دقائق للقراءة

GC.Collect and = null Won't Save You: How the .NET Garbage Collector Really Works

The GC reclaims what nothing can reach, when allocations call for it. Find the reference that keeps memory alive instead of forcing collections.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

After the nightly import, an ASP.NET Core service's memory graph stays high, so a developer adds batch = null; and GC.Collect() at the end of the import "to free memory sooner." The next night, the graph looks the same. The import also takes longer, and the requests that arrive during it see latency spikes. Two weeks later, a heap snapshot finds the real cause: a static list that keeps every imported batch "for the status page." No amount of nulling or collecting could free memory that was still referenced.

The common misconception

The belief: memory in .NET is freed when you let go of an object, so setting references to null as soon as you're done gets memory back sooner. And if memory still looks high, calling GC.Collect() cleans up and makes the app faster.

It feels like responsible engineering. Developers who came from C++ or COM learned to release every object explicitly, and x = null looks like the managed version of delete. Demos seem to prove it: call GC.Collect() and GC.GetTotalMemory drops. And Task Manager shows a big number that doesn't shrink on its own, which looks like something the code should fix.

The trouble is that the GC doesn't work object by object. It doesn't notice when you drop a reference, and it doesn't wait for permission to run.

What actually happens

The GC looks for what's alive, not for what died

During a collection, the GC starts from its : static fields, local variables on thread stacks, CPU registers, GC handles and the finalization queue. It follows every reference from there and marks what it reaches. Everything it didn't reach is garbage, and the GC reclaims that space, compacting the survivors when enough garbage is found. So an object isn't freed when you stop using it. It becomes eligible once no path from any root leads to it, and its memory comes back at a later collection.

Collections are triggered by allocations

A collection starts for one of three reasons: allocations pass a threshold the GC keeps adjusting as the process runs, the machine is low on physical memory, or someone calls GC.Collect(). Setting a reference to null triggers nothing. Microsoft's docs are direct about the third reason: in almost all cases you don't need to call it, because the garbage collector runs continuously.

Generations make most collections cheap

The heap is split into . New objects start in gen 0, which is collected often and quickly, and most objects die there. Survivors are promoted to gen 1, then gen 2. A gen 2 collection is a full collection of the whole heap, and the , where objects of 85,000 bytes or more live, is collected only with gen 2. The design bets on short lives: a request's temporary objects should die young and cost almost nothing.

What = null really does

For a local variable, the JIT decides how long it counts as a root, and optimizations can shorten or lengthen that window. In optimized code, a local can stop counting right after its last use, so x = null at the end of a method is usually noise. Nulling matters in exactly one situation: when it removes the last path from a long-lived root. That means a static field, a singleton, a cache entry or an event subscription, not a local that's about to go out of scope anyway. That's also where real leaks live.

What GC.Collect() really does

The parameterless GC.Collect() performs a full, blocking collection of all generations. Managed threads are suspended while it runs, including the ones serving requests. Every object still alive at that moment, such as the data of in-flight requests, survives and is promoted to an older generation, where it's collected less often and at higher cost. Microsoft's guidance for ASP.NET Core is plain: in general, production apps should not call it.

The import, fixed

Here is the import before and after. The fix doesn't add any GC calls; it removes the reference that kept the data alive:

C# Importer.cs
public static class Importer{    // Kept "for the status page": every batch stays reachable forever    private static readonly List<List<OrderRow>> s_history = [];    public static void Import(IEnumerable<OrderRow> rows)    {        List<OrderRow>? batch = rows.ToList();        Save(batch);        s_history.Add(batch);   // the real reason memory never comes back        batch = null;           // changes nothing: s_history still holds it        GC.Collect();           // a full blocking GC that frees nothing    }    static void Save(List<OrderRow> batch) { /* write to the database */ }}

In the first version, the static list is a root that grows with every import. batch = null only clears a local while the same list stays in s_history, and each GC.Collect() pauses the service to confirm that everything is still reachable. In the second, nothing long-lived points at the rows, so they become garbage the moment Import returns.

Myth vs reality

MythReality
Setting a reference to null frees the objectNothing is freed until a collection runs; nulling helps only if it removes the last path from a root
Nulling locals at the end of a method helps the GCThe JIT already decides when a local stops being a root; the line is noise
GC.Collect() makes the app fasterIt forces a full, blocking collection and promotes everything still alive
High memory in Task Manager means a leakServer GC lets the heap grow for throughput; a leak is memory that never flattens out
The GC frees objects one by one as they dieIt finds what's reachable and reclaims the rest, mostly in cheap gen 0 collections

Read memory graphs correctly

ASP.NET Core apps use Server GC by default. It's tuned for throughput, with a heap and a dedicated GC thread per logical CPU, and it can let the heap grow when memory is available. Since .NET 9, a mode called DATAS is on by default for Server GC; it adapts the heap size to the amount of long-lived data and shrinks it when the load drops. So a high but flat working set is often normal. The sign of a leak is memory that keeps rising and never flattens, even after collections.

How to apply it in your project

  1. Delete GC.Collect callsRemove GC.Collect() from production code paths. If one stays, document the one-off reason and measure that it actually helps.
  2. Stop nulling localsDrop x = null lines for locals and parameters. Keep explicit clean-up only for long-lived holders: clear cache entries, unsubscribe event handlers, and remove items from static collections.
  3. Bound what lives longGive caches a size limit or an expiration, and store summaries instead of full data in anything static or singleton.
  4. Measure before tuningWatch the GC heap size and gen 2 collection counts over time with dotnet-counters, and change GC settings only when the numbers point to a real problem.

Key takeaways

  • The GC reclaims objects that no root can reach, during collections triggered by allocations and memory pressure.
  • = null on a local rarely matters; removing the last reference from a static, cache or event is what frees memory.
  • GC.Collect() forces a full, blocking collection and promotes live objects; keep it out of production code.
  • High memory under Server GC isn't a leak by itself; memory that never flattens is.
  • To fix a leak, find the root that holds the objects instead of forcing collections.

📚 المصادر

  1. Fundamentals of garbage collection — Microsoft Learn
  2. Induced collections — Microsoft Learn
  3. Workstation vs. server garbage collection — Microsoft Learn
  4. Dynamic adaptation to application sizes (DATAS) — Microsoft Learn
  5. Memory management and patterns in ASP.NET Core — Microsoft Learn

التعليقات (0)