1.21 — IDisposable, using, and Finalizers¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.20 Exceptions · Next: 1.22 Anonymous types, dynamic, var
Markers: 🔥 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- The garbage collector handles memory. It does not handle file handles, sockets, or database connections.
IDisposableexists for those. usingguaranteesDispose()gets called, even if an exception is thrown. It compiles down to atry/finally.- Finalizers are a last-resort safety net, not a cleanup mechanism. They make objects live longer and they run at an unpredictable time. Avoid writing them.
The concept¶
.NET's garbage collector automatically frees memory you are no longer using. That covers most things.
But some resources are not memory. A file handle, a network socket, a database connection — these are given out by the operating system, and the operating system has a limited number of them. The garbage collector does not know or care about them.
Worse, the GC runs whenever it feels like it. It might be seconds or minutes before it gets round to your object. In the meantime, that file stays locked and that database connection stays taken out of the pool.
IDisposable is the answer: a standard way for a type to say "I am holding something
that needs releasing — tell me when you are done."
The rule to remember: if a type implements IDisposable, you are responsible for
disposing it.
How it works¶
The using statement¶
using (var stream = new FileStream("data.txt", FileMode.Open))
{
// work with the stream
}
// Dispose() is called here — guaranteed
The compiler expands this into:
var stream = new FileStream("data.txt", FileMode.Open);
try
{
// work with the stream
}
finally
{
stream?.Dispose(); // runs even if an exception was thrown
}
That finally is the whole point. Even if the code inside throws, even if you return
early, Dispose() still runs.
using declarations (C# 8)¶
Since C# 8 you can drop the braces. The object is disposed at the end of the enclosing scope:
public async Task<string> ReadAsync(string path)
{
using var stream = new FileStream(path, FileMode.Open);
using var reader = new StreamReader(stream);
return await reader.ReadToEndAsync();
// Both disposed here, in reverse order: reader first, then stream
}
This removes a lot of nesting. Note the reverse order — the last one created is
disposed first, which is what you want since reader depends on stream.
IAsyncDisposable and await using¶
Some cleanup needs to be asynchronous — flushing a buffer to disk, sending a final network
message. Calling a synchronous Dispose that blocks on async work is a good way to
deadlock or starve the thread pool.
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(ct);
// DisposeAsync() is awaited at the end of scope
If a type offers both, prefer await using. In ASP.NET Core, blocking a thread is
expensive — see 19.12.
Implementing it — the simple case¶
Most of the time, your class just holds other disposable things. Then it is easy:
public sealed class ReportGenerator : IDisposable
{
private readonly FileStream _output;
public ReportGenerator(string path) => _output = File.Create(path);
public void Dispose() => _output.Dispose();
}
Note sealed. If nobody can inherit from your class, you do not need the complicated
pattern below. Sealing is the easiest way to keep disposal simple, and it is what Microsoft
recommends.
The full dispose pattern — only when inheritance is possible¶
If your class is not sealed and holds unmanaged resources directly, you need the full pattern:
public class NativeBuffer : IDisposable
{
private IntPtr _handle; // unmanaged — the GC knows nothing about this
private FileStream? _stream; // managed — the GC handles its memory
private bool _disposed;
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this); // we cleaned up, so skip the finalizer
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
// Called from Dispose(). Safe to touch other managed objects.
_stream?.Dispose();
}
// Always clean up unmanaged resources
if (_handle != IntPtr.Zero)
{
Marshal.FreeHGlobal(_handle);
_handle = IntPtr.Zero;
}
_disposed = true;
}
~NativeBuffer() => Dispose(disposing: false); // finalizer — safety net only
}
Why does disposing exist? Because a finalizer runs on a separate thread at an
unpredictable time, and by then the other managed objects your class references may
already have been collected. Touching them would be a bug. So when disposing is false
(meaning we came from the finalizer), you only clean up unmanaged things.
Why GC.SuppressFinalize? Because if Dispose() already did the work, running the
finalizer later is pointless — and finalizers are expensive. See below.
In practice, you will almost never write this. Wrap unmanaged handles in
SafeHandle, which handles all of it correctly for you.
Why finalizers are bad¶
An object with a finalizer costs significantly more:
- When it is created, it goes on a special "needs finalizing" queue.
- When the GC would normally collect it, it cannot — it has to run the finalizer first.
- So the object is promoted to the next generation and survives longer.
- A separate finalizer thread runs the method at some unpredictable later point.
- Only on the next garbage collection is the memory actually freed.
So a finalizer means your object survives at least two collections instead of one. Add a finalizer to a frequently created type and you can measurably hurt performance.
A finalizer is a safety net for when someone forgets to call Dispose. It is not a
cleanup strategy.
Who disposes what in ASP.NET Core¶
This comes up a lot. The DI container disposes services it created, when their scope ends:
builder.Services.AddScoped<MyDisposableService>();
// Container creates it, container disposes it at the end of the request.
// You do NOT dispose it yourself.
builder.Services.AddSingleton(new MyDisposableService());
// YOU created this instance and handed it over.
// The container does NOT dispose it. It is yours to manage.
And the important exception: never dispose an HttpClient from IHttpClientFactory.
The factory manages the underlying handler's lifetime, and disposing it defeats the entire
mechanism. See 19.10.
Interview questions¶
Q: What is IDisposable for, when we already have a garbage collector?
The garbage collector manages memory, and it does that well. But it knows nothing about
resources that are not memory — file handles, sockets, database connections, operating
system handles. Those are limited, and holding them too long causes real problems like
locked files and exhausted connection pools. The GC also runs at an unpredictable time, so
even for things it could eventually clean up, "eventually" is not good enough. IDisposable
gives you a standard way to say "release this now", and using guarantees it happens even
if an exception is thrown.
Q: What does the using statement compile to?
A try/finally. The object is created before the try, and Dispose() is called in the
finally block with a null check. That is why it works even when the body throws or returns
early. The C# 8 using declaration form without braces does the same thing, disposing at
the end of the enclosing scope, in reverse order of creation.
Q: What is a finalizer and when would you write one?
A finalizer is a method the garbage collector calls before reclaiming an object, written as
~ClassName(). Almost never write one. It makes the object survive at least one extra
garbage collection, because the GC has to put it on a queue and run the finalizer on a
separate thread before it can free the memory. It also runs at an unpredictable time, and
by then other managed objects it references may already be gone. The only legitimate use is
as a last-resort safety net for an unmanaged handle held directly — and even then,
SafeHandle does the job properly and you should use that instead.
Q: What is GC.SuppressFinalize and why is it in the dispose pattern?
It tells the garbage collector not to bother running this object's finalizer. You call it
at the end of Dispose() because if Dispose has already cleaned everything up, running
the finalizer afterwards is pure waste — and finalizers are expensive, keeping the object
alive for an extra collection cycle. So it turns the "someone forgot to dispose" penalty
back off when they did remember.
Q: In ASP.NET Core, who is responsible for disposing services?
The container disposes anything it created, when the owning scope ends — so a scoped
service is disposed at the end of the request and a singleton at application shutdown. But
if you register an instance you built yourself, with AddSingleton(new Thing()), the
container does not take ownership and you have to manage it. The other case worth knowing
is HttpClient from IHttpClientFactory — you should never dispose those, because the
factory is managing the underlying handler pool.
Traps ⚠️¶
- Forgetting to dispose. No error, no warning at runtime — just leaked handles and exhausted connection pools under load.
- Disposing something the container owns. Causes "cannot access a disposed object" on the next request.
- Disposing an
HttpClientfromIHttpClientFactory. Defeats the whole point of the factory. - Writing a finalizer when you do not need one. It makes every instance more expensive and delays collection.
- Calling
Dispose()inside a finalizer without thedisposingflag. The managed objects you are touching may already be collected. Dispose()must be safe to call more than once. The guard flag exists for this reason; throwing on a second call breaks callers.- A synchronous
Disposethat blocks on async work can deadlock or starve the thread pool. ImplementIAsyncDisposableinstead. usingon a null variable is fine. The generated code null-checks it.
Related¶
- 1.20 Exceptions —
usingversusfinally - 1.12 Events —
Disposeis where you unsubscribe - 3.4 Garbage collection — why finalizers cost so much
- 6.10 Disposal in DI — who owns what in ASP.NET Core
- 19.10 HttpClientFactory — the client you must not dispose