Skip to content
Tutorials Center
My learning

Topics

Lesson 88 of 182 ยท Null Safety and Errors

IDisposable, using and Finalizers

Learn how C# releases files, connections and other resources with IDisposable, using statements and declarations, the dispose pattern, finalizers and await using.

The garbage collector frees memory for you, and that is one of the best things about C#. But memory is not the only thing a program borrows. A file handle, a network socket, a database connection, a lock on a resource or a block of unmanaged memory all have to be handed back, and the garbage collector does not know when you are done with them. If you wait for it to notice, a file may stay locked for seconds, a connection pool may run dry, and a server may fall over under load.

C# solves this with a small contract, the IDisposable interface, and a piece of syntax that guarantees the cleanup runs: the using statement. This lesson explains the problem, the contract, the syntax, the full dispose pattern that library authors use, finalizers (and why you rarely write them) and the asynchronous twin, IAsyncDisposable. It builds on exceptions, because the whole point of using is to clean up correctly when an exception flies past.

Managed memory versus resources

The garbage collector (GC) reclaims objects that nothing references any more. It runs when it decides memory is tight, which could be in a millisecond or in a minute. That is fine for memory, because nobody cares exactly when a dead List<int> disappears.

A resource is something scarce that lives outside the GC's knowledge: an operating system file handle, a socket, a database connection, a GPU buffer. These have two properties that memory does not:

  • There are a limited number of them (a process can open only so many files).
  • Holding them has visible side effects (an open file blocks other writers, an open transaction blocks other users).

The rule for such resources is deterministic cleanup: release them at a moment you control, not at a moment the GC picks. In C# that means calling Dispose().

The IDisposable contract

IDisposable has exactly one member:

C#
public interface IDisposable
{
    void Dispose();
}

A type that implements it says: "I own something that needs releasing. When you are finished with me, call Dispose()." Streams, readers, writers, HttpClient, database connections, timers and many more types in the .NET library implement it. Your IDE and analyzers (rule CA2000 and friends) warn you when you create one and never dispose it.

Let's build a tiny resource so we can watch what happens. It prints when it is opened and when it is closed.

C# A resource and a manual Dispose call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This works, but it is fragile. If log.Write("working") threw an exception, the call to Dispose() would be skipped and the "file" would stay open. The classic fix is try/finally.

try/finally, the hand-written way

A finally block runs whether the try block finishes normally, returns early or throws. Putting Dispose() there makes cleanup reliable.

C# Cleanup with try/finally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output shows the order: open, step 1, the exception is caught, and only then the logger closes. That is correct, but writing try/finally around every resource is noisy and easy to forget. That is exactly what using is for.

The using statement

using (resource) { ... } is shorthand for a try/finally that calls Dispose() on the resource at the end of the block, even when an exception occurs or you return from inside it.

C# The using statement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at the second block: the logger is closed ([close] broken.log) before the catch handler prints its message, because leaving the using block, even by an exception, disposes the resource first. The variable declared in the parentheses is read-only inside the block, so you cannot accidentally reassign it and leak the original.

Using declarations (C# 8)

Since C# 8 you can drop the braces and write using var x = ...;. The resource is disposed when the enclosing scope ends: the end of the method, the loop body or whatever block contains the declaration. This removes a level of nesting and is the form most modern code uses.

C# Using declarations and disposal order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Resources are disposed in reverse order of declaration: second closes before first. That mirrors how nested blocks unwind, and it is what you want when a later resource depends on an earlier one (a reader depends on its stream).

Use the declaration form by default. Switch to the braced statement when you want the resource released earlier than the end of the method, for example to let another piece of code reopen a file you just finished writing.

Disposing real library objects

The same syntax works for the types in the library. StringWriter, StreamReader, MemoryStream and FileStream are all IDisposable. Files can be created in the current directory during a run, so this example really writes and reads one.

C# Writing and reading a file with using

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The writer is in a braced using on purpose. It buffers text and only guarantees the data reached the file when it is disposed (or flushed). If we had kept the writer open and tried to open the file again for reading, the second open could fail because the first handle still holds it.

What Dispose must (and must not) do

A good Dispose method follows a few rules that make it safe for callers:

  1. It is idempotent. Calling Dispose() twice must not throw or release things twice. Callers cannot always know whether someone else already disposed the object.
  2. It does not throw in normal circumstances. It often runs inside a finally block while another exception is in flight, and a second exception would hide the original.
  3. It releases what the object owns and, for composite objects, disposes the IDisposable fields it created.
  4. After disposal, other members throw ObjectDisposedException. Use ObjectDisposedException.ThrowIf(_disposed, this) at the start of public methods.

Here is a compact, correct implementation for a class that owns another disposable.

C# A correct simple Dispose

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that using var store triggers a third call to Dispose() at the end of the program. Because the method returns early when _disposed is true, nothing breaks and nothing prints twice.

Finalizers: the safety net

A finalizer (written like a destructor, ~TypeName()) is a method the GC calls on an object after it has decided the object is garbage. Its purpose is to release unmanaged resources in case the programmer forgot to call Dispose().

C#
class Risky
{
    ~Risky()
    {
        // last-chance cleanup, runs on the finalizer thread at an unpredictable time
    }
}

Finalizers are a safety net, not a plan:

  • Timing is unpredictable. It may run long after the object became unreachable, or never at all if the process exits first (finalizers are not guaranteed to run on exit in modern .NET).
  • They are costly. Objects with finalizers survive one extra collection and go through the finalization queue, which slows the GC.
  • They run on a special thread, in no defined order relative to other finalizers, so a finalizer must never touch other managed objects that might already be finalized.
  • Exceptions in a finalizer crash the process.

For almost all code the correct advice is: do not write a finalizer. You only need one when your class directly owns an unmanaged resource such as a raw handle, and even then the better tool is a SafeHandle (see below). Let's watch a finalizer run, with the caveat that the exact moment is up to the runtime. We force a collection here only to demonstrate it; production code should never call GC.Collect().

C# A finalizer as a safety net

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The remembered object printed disposed remembered and told the GC with GC.SuppressFinalize(this) that the finalizer is no longer needed, so it never ran. The forgotten one was cleaned up by its finalizer instead, which is exactly the safety-net behavior, though a real program should not depend on it.

The full dispose pattern

When a class owns both managed disposable objects and unmanaged resources, or when it is meant to be inherited, Microsoft's guidelines recommend the dispose pattern. It splits the work into a public Dispose() and a protected virtual Dispose(bool disposing):

  • disposing == true means a caller invoked Dispose(): release managed fields and unmanaged resources.
  • disposing == false means the finalizer is calling: release only unmanaged resources, because managed fields may already be finalized.
C# The classic dispose pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first connection shows the happy path (disposing=True). The second was abandoned, so only the unmanaged part is released by the finalizer (disposing=False) and the managed buffer is left to the GC.

Honestly, you will seldom write this by hand. If your class only wraps other IDisposable objects, the simple version from earlier (no finalizer, sealed class or no virtual method) is enough. Make a class sealed whenever you can; it removes the need for the virtual method.

SafeHandle

Directly holding a raw handle in a field is risky: the GC could finalize your object while a native call using the handle is still running. System.Runtime.InteropServices.SafeHandle is a base class that wraps a handle and gets the finalization right. Libraries such as FileStream use it internally. In everyday code you will use the high-level types and never subclass SafeHandle yourself; you only meet it when calling native APIs (see the interop topics later in the course).

IAsyncDisposable and await using

Some cleanup is itself asynchronous: flushing a buffer to the network, or closing a connection politely. Calling a blocking Dispose() for that would block a thread. For this, .NET offers IAsyncDisposable with a single method, ValueTask DisposeAsync(), and the matching syntax await using (C# 8).

C# await using and IAsyncDisposable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If a type implements both IDisposable and IAsyncDisposable, prefer await using inside async methods. Many library types (Stream, DbConnection, Utf8JsonWriter) offer both. A class that implements IAsyncDisposable for a base class should usually call a shared DisposeAsyncCore() method; the details are covered together with async patterns and pitfalls.

Common pitfalls

  • Forgetting to dispose. The most common leak. Turn on analyzers (CA2000, CA1001) and treat their warnings seriously.
  • Disposing something you do not own. If a method receives a stream as a parameter, the caller normally owns it. Only dispose what you created, unless the API documents a transfer of ownership.
  • Returning a disposed object. using var x = Create(); return x; hands back an already-closed object. Return it directly and let the caller dispose it.
  • Disposing in a loop incorrectly. A using var inside a loop body is disposed at the end of each iteration, which is usually what you want. Declaring it outside the loop keeps one resource for all iterations.
  • Long-lived HttpClient surprises. HttpClient is disposable, but creating a new one per request exhausts sockets. Share one instance, or use IHttpClientFactory (see the dependency injection chapter). Disposal is a rule with exceptions, so read the documentation of types you use heavily.
  • Throwing from Dispose. If cleanup can fail (a flush that hits a full disk), consider exposing an explicit Close() or Flush() that can throw, and keep Dispose() quiet.

Never assume the finalizer will save you in a server. Under load the GC may delay finalization for a long time, and the scarce resource (connections, handles) runs out long before. Always dispose deterministically.

When to use what

Situation Use
A class that only owns other disposable objects IDisposable, simple Dispose(), sealed, no finalizer
Raw unmanaged handle SafeHandle instead of a finalizer
Cleanup that needs await IAsyncDisposable and await using
Base class designed for inheritance Dispose pattern with protected virtual Dispose(bool)
Cleanup of a small piece of state (not a resource) try/finally, not IDisposable

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a using statement guarantee?

    using expands to a try/finally that calls Dispose, so cleanup runs on normal exit, return and exceptions. It does not free memory by itself and does not use another thread.
  2. 2. In which order are two using declarations in the same method disposed?

    Using declarations unwind like nested blocks, so the last declared resource is disposed first. That is what you want when later resources depend on earlier ones.
  3. 3. Why is a finalizer not a replacement for calling Dispose?

    The GC decides when (or whether) finalizers run, so a file or connection can stay open for a long time. Deterministic Dispose releases it exactly when you are done.
  4. 4. What is the purpose of GC.SuppressFinalize(this) inside Dispose?

    After Dispose has done the cleanup, running the finalizer would be redundant and costly, so the object is removed from the finalization queue.
  5. 5. When should you use await using instead of using?

    await using calls DisposeAsync, which returns a ValueTask. It suits resources whose cleanup involves asynchronous work such as flushing to a network or database.

Summary

  • The GC reclaims memory, not scarce resources such as files, sockets and connections. Release those deterministically with Dispose().
  • IDisposable has one method. Implement it so it is idempotent, quiet and releases everything the object owns; throw ObjectDisposedException on use after disposal.
  • using (statement or C# 8 declaration) is a try/finally that guarantees Dispose(). Declarations dispose in reverse order at the end of the scope.
  • Finalizers are a rarely needed safety net for unmanaged resources; prefer SafeHandle, and call GC.SuppressFinalize from Dispose() when you have one.
  • The full dispose pattern (Dispose(bool disposing)) is for inheritable classes or classes holding unmanaged resources; otherwise keep it simple and sealed.
  • Use IAsyncDisposable and await using when cleanup is asynchronous.

Next: Validating Input and Defensive Programming