
GC.Collect and = null Won't Save You: How the .NET Garbage Collector Really Works
- كاتب موثّق
- .NET 10
محتويات المقال
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
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.
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.
What actually happens
The GC looks for what's alive, not for what died
Collections are triggered by allocations
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
What = null really does
= null really doesx = 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
GC.Collect() really doesGC.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
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 */ }}public static class Importer{ // The status page only needs a summary, not the rows public static ImportSummary? LastImport { get; private set; } public static void Import(IEnumerable<OrderRow> rows) { var batch = rows.ToList(); Save(batch); LastImport = new(batch.Count, DateTimeOffset.UtcNow); // No null, no GC.Collect: once Import returns, nothing reaches // the batch, and a later collection reclaims it when space is needed } static void Save(List<OrderRow> batch) { /* write to the database */ }}public record ImportSummary(int Rows, DateTimeOffset At);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
null frees the object | |
GC.Collect() makes the app faster | |
Read memory graphs correctly
How to apply it in your project
Delete GC.Collect calls Remove GC.Collect()from production code paths. If one stays, document the one-off reason and measure that it actually helps.Stop nulling locals Drop x = nulllines 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.Bound what lives long Give caches a size limit or an expiration, and store summaries instead of full data in anything static or singleton. Measure before tuning Watch 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. = nullon 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.
التعليقات (0)