
What the Garbage Collector Won't Clean Up: IDisposable Explained
- كاتب موثّق
- .NET 10
محتويات المقال
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
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.
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.
What actually happens
The GC frees memory, and only memory
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
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
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
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
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}var path = Path.Combine(Path.GetTempPath(), "orders.csv");Export(path, ["1,10.50", "2,42.00"]);Console.WriteLine(new FileInfo(path).Length); // 18: both rows are on diskExport(path, ["3,7.25"]); // works: the first handle is closedstatic void Export(string path, string[] rows){ using var writer = new StreamWriter(path); // disposed when Export returns foreach (var row in rows) { writer.WriteLine(row); }} // Dispose flushes the buffer, then closes the handle, even after an exceptionusing 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
Dispose; at most, it runs a finalizer | |
Dispose only delays cleanup | Dispose |
SafeHandle instead |
Who calls Dispose
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.
IDisposable and passes the call on. A sealed class like this needs no Dispose(bool) and no finalizer:
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}How to apply it in your project
Turn on the dispose rules Enable CA2000 and CA2213 as warnings, build, and go through the list: each entry releases its resources late or never. Give every disposable an owner Wrap locals in usingorawait using. When a class creates and stores a disposable, make that classIDisposabletoo, and dispose the field in itsDispose.Don't write finalizers Remove finalizers from classes that hold only managed objects. If you really wrap a raw handle, derive from SafeHandleinstead.Watch resources, not just memory Graph 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: usingfor locals,IDisposableon the class for fields.
📚 المصادر
Cleaning up unmanaged resources — Microsoft Learn Implement a Dispose method — Microsoft Learn using statement: ensure the correct use of disposable objects — Microsoft Learn Finalizers (C# programming guide) — Microsoft Learn SQL Server connection pooling with Microsoft.Data.SqlClient — Microsoft Learn
التعليقات (0)