Skip to content

Resource management in C#: using and await using

The garbage collector frees memory, but it does not know when to close a file, return a database connection to the pool or flush a network buffer. Those resources need deterministic cleanup: at a known point, even when an exception is thrown. This page covers the three C# forms that guarantee it: the classic using statement, the shorter using declaration, and await using for resources whose cleanup is itself asynchronous.

Every complete sample is a file-based program: save it as sample.cs and run dotnet run sample.cs with the .NET 10 SDK (C# 14). All samples on this page were compiled and run with .NET SDK 10.0.115.

Feature Version Use it when
Using statement C# 1 You want an explicit block that ends exactly where cleanup should happen.
Using declarations C# 8 The resource should live until the end of the current method or block.
Await using C# 8 The resource implements IAsyncDisposable and cleanup does I/O.

Introduced in C# 1 (.NET Framework 1.0). using (var resource = ...) { ... } calls resource.Dispose() when control leaves the block, whether it ends normally, returns early or throws. The compiler expands it to a try/finally, so you get the same guarantee without writing the boilerplate. The resource must implement IDisposable (or, for a ref struct, have an accessible Dispose method since C# 8).

Several resources can be stacked, and they are disposed in reverse order of acquisition, which matters when one depends on another (a writer on top of a stream). The variable declared in the statement is read-only inside the block, so it cannot be reassigned to a different object that would then escape disposal. If the expression evaluates to null, no Dispose call is made and no exception is thrown.

try
{
using (var export = new ExportFile("orders.csv"))
using (var audit = new ExportFile("audit.log"))
{
export.Write("1001,Ada Lopez,250.00");
audit.Write("exported 1001");
throw new InvalidOperationException("disk full");
}
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Caught: {ex.Message}");
}
ExportFile? optional = null;
using (optional) // null resource: no Dispose call, no exception
{
Console.WriteLine("No optional export this run");
}
sealed class ExportFile(string name) : IDisposable
{
public void Write(string line) => Console.WriteLine($" {name} <- {line}");
public void Dispose() => Console.WriteLine($" {name} closed");
}

Output:

orders.csv <- 1001,Ada Lopez,250.00
audit.log <- exported 1001
audit.log closed
orders.csv closed
Caught: disk full

Both files are closed before the catch block runs, in reverse order. The last line, No optional export this run, is also printed.

Pitfalls:

  • Disposal is not cancellation. Dispose runs after the block finishes; it does not stop work in progress on another thread.
  • Do not dispose what you do not own. A shared HttpClient or an injected DbContext belongs to its creator or the DI container.
  • Construct inside the statement. var s = Open(); using (s) { ... } leaves a gap where an exception between the two lines leaks the resource.

Introduced in C# 8 (.NET Core 3.0). A using declaration, using var reader = ...;, has the same guarantee as the statement but no block of its own: the resource is disposed at the end of the enclosing scope, usually the method. Several declarations in one scope are disposed in reverse order of declaration. This removes the nesting that stacked using blocks create and keeps the “happy path” of a method flat.

The trade-off is lifetime. A connection declared at the top of a long method stays open until the method returns, even if it was only needed for the first few lines. When cleanup should happen earlier, put the declaration in a smaller block (an if body or a bare { }) or use the statement form.

Console.WriteLine($"Report has {BuildReport()} lines");
static int BuildReport()
{
using var connection = new Tracked("db connection");
using var reader = new Tracked("order reader");
Console.WriteLine(" reading orders");
int lines = 3;
if (lines > 0)
{
using var temp = new Tracked("temp buffer");
Console.WriteLine(" formatting");
} // temp is disposed here, at the end of its block
Console.WriteLine(" totals computed");
return lines;
} // reader, then connection, are disposed here
sealed class Tracked : IDisposable
{
private readonly string _name;
public Tracked(string name) { _name = name; Console.WriteLine($" open {name}"); }
public void Dispose() => Console.WriteLine($" dispose {_name}");
}

Output:

open db connection
open order reader
reading orders
open temp buffer
formatting
dispose temp buffer
totals computed
dispose order reader
dispose db connection
Report has 3 lines

Pitfalls:

  • Returning the resource. using var stream = File.OpenRead(path); return stream; hands the caller an already-disposed object. Only the owner should declare it with using.
  • Lazy enumerables. In an iterator method (yield return), the declaration lives until enumeration finishes or the enumerator is disposed, not until the method “returns”.
  • Not allowed in a switch case section without braces, because the case has no scope of its own.

Introduced in C# 8 (.NET Core 3.0). Some cleanup is I/O: flushing a buffered upload, committing a final batch, closing a network stream gracefully. Doing that synchronously in Dispose blocks a thread. IAsyncDisposable.DisposeAsync() returns a ValueTask, and await using awaits it at the end of the scope, in both statement form (await using (var x = ...) { }) and declaration form (await using var x = ...;).

It only works in an async method and only on types that implement IAsyncDisposable or have a suitable DisposeAsync method; a type with only Dispose gives error CS8417. Many .NET types implement both interfaces (FileStream, StreamWriter, ADO.NET connections and transactions), and in async code you should prefer the async path. To control context capture, write await using (resource.ConfigureAwait(false)).

await ExportAsync(["1001,250.00", "1002,80.00"]);
static async Task ExportAsync(string[] rows)
{
await using var writer = new BufferedUploadWriter("exports/orders.csv");
foreach (string row in rows)
{
await writer.WriteLineAsync(row);
}
Console.WriteLine(" rows queued");
} // await writer.DisposeAsync() runs here
sealed class BufferedUploadWriter(string path) : IAsyncDisposable
{
private readonly List<string> _buffer = [];
public Task WriteLineAsync(string line)
{
_buffer.Add(line);
return Task.CompletedTask;
}
public async ValueTask DisposeAsync()
{
await Task.Delay(10); // stands in for the network flush
Console.WriteLine($" flushed {_buffer.Count} rows to {path}");
}
}

Output:

rows queued
flushed 2 rows to exports/orders.csv

Pitfalls:

  • Plain using on an async-only type does not compile. If a type implements only IAsyncDisposable, using reports an error rather than silently skipping cleanup; implement IDisposable too if synchronous callers exist.
  • Exceptions in DisposeAsync. An exception thrown during disposal replaces one thrown in the body; keep disposal code defensive.
  • Await every ValueTask once. Do not store the result of DisposeAsync() and await it twice.
  • Default in modern code: a using declaration, because it keeps methods flat.
  • Need cleanup before the method ends: a using statement, or a declaration inside a smaller block.
  • In an async method with a resource that implements IAsyncDisposable: await using, in either form.
  • Writing a disposable type: implement IDisposable; add IAsyncDisposable when cleanup does I/O. Follow the Dispose pattern only if you hold unmanaged handles directly.

What does a using statement compile to? A try/finally in which the finally calls Dispose on the resource if it is not null. That is why disposal runs on early returns and exceptions.

In what order are multiple resources disposed? In reverse order of acquisition, for both stacked statements and several declarations in one scope. Later resources often depend on earlier ones, so they must be closed first.

When is a using var declaration disposed? At the end of the enclosing scope (usually the method), not after its last use. Wrap it in a smaller block if it should be released sooner.

What is the difference between Dispose and a finalizer? Dispose is called deterministically by your code (or using). A finalizer is called by the GC at an unknown time, only as a safety net for unmanaged resources. Types that release resources in Dispose call GC.SuppressFinalize(this) so the finalizer does not also run.

Why does IAsyncDisposable.DisposeAsync return ValueTask rather than Task? Disposal usually completes synchronously (nothing left to flush), and ValueTask avoids allocating a Task in that common case.

Senior scenario: OrdersPortal’s nightly export occasionally runs out of database connections under load. What would you look at? Connections are pooled, so exhaustion usually means connections are not returned quickly. Check that every connection, command and reader is disposed with using or await using and that none is declared at the top of a long method that then does slow, unrelated work. Look for connections captured by lazily enumerated queries that are never fully enumerated, and for code that blocks on async database calls and holds connections while threads starve. Keep each connection’s lifetime to the unit of work that needs it, and measure pool usage with the provider’s event counters.