الانتقال إلى المحتوى
.NETC#· 8 دقائق للقراءة

What the Garbage Collector Won't Clean Up: IDisposable Explained

The GC frees memory, not files, connections or buffers. Why a forgotten Dispose is cleaned up late or never, and who owns the call.

ReadIn

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

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

A worker service exports the day's orders to a CSV file that a partner downloads every morning. Some days the file stops a few rows short, cut off mid-line. When the job retries, it fails with "The process cannot access the file because it is being used by another process." Memory is fine, the CPU is idle and the logs show nothing else. The export method creates a StreamWriter, writes the rows and returns. It never calls Dispose, because the team assumed the garbage collector would close the file once the writer went out of scope.

The common misconception

The belief: Dispose is a memory optimization. It frees things a little sooner, but if you forget it, the garbage collector notices the object is gone and cleans up everything it held. In a managed language, you'd have to work hard to leak anything.

It's a reasonable conclusion. Most objects you create are never disposed and nothing bad happens, because all they hold is memory. Some disposable types really do have a fallback: a FileStream that nobody disposes does close its file handle eventually. And in a quick test, a forgotten Dispose rarely shows a symptom, because the process exits before anything runs out.

The trouble is the word "eventually". The GC was built to manage one resource, memory, and it decides when to run by looking at memory alone.

What actually happens

The GC frees memory, and only memory

A FileStream is a small object on the managed heap that holds an operating system file handle. A SqlConnection is a small object that holds a network connection to the database, borrowed from a . The GC can tell when the small object is unreachable and reclaim its bytes, but it has no idea how to close a file or return a connection. Microsoft's docs put it plainly: the GC can track the lifetime of an object that wraps an , but it doesn't know how to release that resource. Releasing it is the job of Dispose.

Collections follow memory pressure, not handle pressure

The GC runs when allocations cross its thresholds or the machine runs low on memory. Running out of file handles or pooled connections triggers nothing, and an abandoned writer or connection is a tiny object, so a service with free memory can go a long time between collections while those resources stay taken. SqlClient's pool allows 100 connections by default; once all of them are checked out, the next Open waits up to 15 seconds for one to come back, then fails with "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool." SqlClient can reclaim a connection nobody disposed, but only after the GC has collected the abandoned object. Under load, that's far too late.

Finalizers are a late safety net

Types that wrap a handle directly, usually through a SafeHandle, have a : a method the GC calls at some point after it finds the object unreachable. That's how the export's file is released in the end. But the exact time a finalizer runs is undefined, so is the thread it runs on, and since .NET 5, finalizers don't run at all when the process exits. Microsoft's guidance treats the finalizer as a safeguard for when Dispose wasn't called, never as the plan.

Some cleanup happens only in Dispose

The GC never calls Dispose. A finalizer, when a type has one, only releases the raw handle, so everything else a type does in Dispose simply doesn't happen. StreamWriter keeps text in a buffer and writes it to the file on Flush or Dispose. No finalizer flushes it, so rows still in the buffer when the writer is abandoned are lost, even after a collection. The same goes for removing an item from a shared collection or releasing a lock: if Dispose doesn't run, nobody does it.

The export, fixed

Here is the export before and after. Both versions write two rows, check the file size, then export again:

C# Program.cs
var path = Path.Combine(Path.GetTempPath(), "orders.csv");Export(path, ["1,10.50", "2,42.00"]);Console.WriteLine(new FileInfo(path).Length); // 0: rows still bufferedExport(path, ["3,7.25"]); // IOException: file is in use by another processstatic void Export(string path, string[] rows){    var writer = new StreamWriter(path); // opens an OS file handle    foreach (var row in rows)    {        writer.WriteLine(row);    }    // no Dispose: nothing flushes the buffer or closes the handle}

In the first version, both rows sit in the writer's buffer, so the file is empty. On Windows, the second export can't even open the file, because the first handle is still open. It closes only when a collection happens to run and the handle's finalizer gets to it, and the buffered rows are lost even then. In the second version, the using declaration disposes the writer when Export returns. The compiler turns it into a try/finally, so an exception halfway through still flushes what was written and closes the file.

Myth vs reality

MythReality
The GC disposes the objects it collectsThe GC never calls Dispose; at most, it runs a finalizer
A forgotten Dispose only delays cleanupSome cleanup, like flushing a buffer, happens only in Dispose
The GC will run soon enoughIt runs when memory is needed; running out of handles or connections doesn't trigger it
Finalizers always run in the endSince .NET 5, they don't run when the process exits
A safe class needs its own finalizerOnly a class that owns a raw handle; wrap it in a SafeHandle instead

Who calls Dispose

The rule is ownership: whoever creates a disposable object and keeps it is responsible for disposing it. For a local, that's a using declaration or a using block, which dispose even when an exception is thrown, in reverse order when you declare several. For an IAsyncDisposable such as a database connection, use await using.

For a field, the class that creates and stores the disposable becomes its owner, so it implements IDisposable and passes the call on. A sealed class like this needs no Dispose(bool) and no finalizer:

C# OrderExporter.cs
public sealed class OrderExporter(string path) : IDisposable{    private readonly StreamWriter _writer = new(path); // created here: owned    public void Write(string row) => _writer.WriteLine(row);    public void Dispose() => _writer.Dispose(); // pass the cleanup on}

Services you get from dependency injection are the exception. The container disposes the ones it creates at the end of their lifetime, so a class that receives a service through its constructor doesn't dispose it.

How to apply it in your project

  1. Turn on the dispose rulesEnable CA2000 and CA2213 as warnings, build, and go through the list: each entry releases its resources late or never.
  2. Give every disposable an ownerWrap locals in using or await using. When a class creates and stores a disposable, make that class IDisposable too, and dispose the field in its Dispose.
  3. Don't write finalizersRemove finalizers from classes that hold only managed objects. If you really wrap a raw handle, derive from SafeHandle instead.
  4. Watch resources, not just memoryGraph open handles and pooled connections in use next to memory. A disposal bug shows up there long before it shows up in memory.

Key takeaways

  • The GC frees memory only; files, sockets, pooled connections and buffers are released by Dispose.
  • Collections follow memory pressure, so leaked handles and connections can stay taken long enough to break the app.
  • Finalizers are a late safety net that doesn't run at process exit, and some cleanup, like flushing a StreamWriter, has no fallback at all.
  • If you create and keep a disposable, you own it: using for locals, IDisposable on the class for fields.

📚 المصادر

  1. Cleaning up unmanaged resources — Microsoft Learn
  2. Implement a Dispose method — Microsoft Learn
  3. using statement: ensure the correct use of disposable objects — Microsoft Learn
  4. Finalizers (C# programming guide) — Microsoft Learn
  5. SQL Server connection pooling with Microsoft.Data.SqlClient — Microsoft Learn

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