Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# await using: Asynchronous Resource Disposal

Learn how to use C# await using to dispose IAsyncDisposable resources asynchronously, with syntax, examples, and practical guidance.

~4 min readC#
#IAsyncDisposable#async disposal#resource management#C# using
Illustration of C# await using for asynchronous resource disposal with a shield and clock metaphor.

When a type implements IDisposable, the using statement guarantees that Dispose() is called when the block exits. Some resources, such as file streams, network streams, or database connections, can benefit from asynchronous cleanup. C# 8.0 introduced await using to handle this scenario through the IAsyncDisposable interface. This article explains how await using works, how to implement the interface, and when to prefer it over using.

What Problem Does await using Solve?

Synchronous Dispose() can block the calling thread when the cleanup operation involves I/O, such as flushing a buffer or closing a stream. In an asynchronous application, blocking the thread during cleanup defeats the purpose of using async I/O. IAsyncDisposable provides an asynchronous DisposeAsync() method that can perform cleanup without blocking. The await using statement ensures that DisposeAsync() is called and awaited when the scope exits.

The IAsyncDisposable Interface

The interface is defined in the System namespace and looks like this:

csharp
public interface IAsyncDisposable { ValueTask DisposeAsync(); }

The method returns ValueTask rather than Task to minimize allocation when disposal completes synchronously. A type that owns an asynchronous resource implements this interface and performs its cleanup inside DisposeAsync().

Here is a minimal implementation that delegates disposal to a FileStream:

csharp
public class AsyncResource : IAsyncDisposable { private readonly FileStream _stream; public AsyncResource(string path) { _stream = File.OpenRead(path); } public async ValueTask DisposeAsync() { await _stream.DisposeAsync(); } }

FileStream.DisposeAsync() is available in .NET Core 3.0 and later. If the owned resource has its own asynchronous cleanup method, DisposeAsync() can call that method instead.

Basic Syntax of await using

The syntax mirrors the traditional using statement but adds await before using:

csharp
await using (var resource = new AsyncResource("data.txt")) { // Use the resource }

When the block exits, the compiler generates code that calls DisposeAsync() and awaits the returned ValueTask. The await using statement also works with the declaration form:

csharp
await using var resource = new AsyncResource("data.txt"); // Use the resource // DisposeAsync is called when the variable goes out of scope

The declaration form is convenient when the resource should be disposed at the end of the current scope, such as the end of a method or a loop iteration.

How the Compiler Transforms await using

The compiler expands await using into a try/finally block, similar to the synchronous using, but with an asynchronous disposal call. The generated code checks whether the resource is null and then awaits DisposeAsync():

csharp
var resource = new AsyncResource("data.txt"); try { // Use the resource } finally { if (resource != null) { await resource.DisposeAsync(); } }

This transformation ensures that disposal happens even if an exception is thrown inside the block. The await keyword in the finally block is allowed because the entire method is async. This is a key difference from the synchronous using, where Dispose() is called without awaiting.

Common Mistakes and Pitfalls

One common mistake is using await using with a type that only implements IDisposable but not IAsyncDisposable. The compiler will raise an error because the type cannot be used with await using. You must ensure the type implements IAsyncDisposable.

Another pitfall is mixing using and await using for the same type. If a type implements both interfaces, using will call Dispose() and await using will call DisposeAsync(). These two cleanup paths can behave differently, so decide which one is appropriate for the resource and be consistent.

Also, be careful with await using in a loop. Each iteration creates a new scope, so the resource is disposed at the end of each iteration. If you need to reuse a resource across iterations, declare it outside the loop.

Performance and Runtime Considerations

await using introduces a small overhead compared to synchronous using because it involves awaiting a ValueTask. However, the overhead is negligible in most applications. The main performance benefit is that it prevents blocking the thread during cleanup, which can be significant when dealing with high-latency I/O.

The ValueTask returned by DisposeAsync() can be completed synchronously if the cleanup does not need to yield. In that case, awaiting it does not cause a thread switch or additional allocation.

One thing to keep in mind is that DisposeAsync() should not throw exceptions unless absolutely necessary. If it does, the exception will propagate from the await using block, potentially masking the original exception if one was thrown inside the block. This is similar to the behavior of synchronous Dispose().

When to Use await using vs using

Use await using when the type implements IAsyncDisposable and the cleanup involves asynchronous operations, such as closing a network stream, flushing a buffer to disk, or releasing a database connection. If the cleanup is purely in-memory and does not require I/O, the synchronous Dispose() is usually sufficient and avoids the extra await.

For types that implement both interfaces, choose the one that matches the resource's actual cleanup requirements. If the cleanup is inherently asynchronous, use await using. If it is synchronous, use using. Mixing them can lead to subtle bugs.

Advanced Usage: Implementing IAsyncDisposable with Both Dispose Paths

When a class holds both a resource that supports asynchronous disposal and a resource that only supports synchronous disposal, it can implement both IDisposable and IAsyncDisposable. The important requirement is that both cleanup paths are idempotent, and that each path disposes every resource it owns so the caller cannot accidentally skip a cleanup.

Here is an example:

csharp
public sealed class MixedResource : IDisposable, IAsyncDisposable { private readonly FileStream _fileStream; private readonly IDisposable _syncResource; private bool _disposed; public MixedResource(string filePath, IDisposable syncResource) { _fileStream = File.OpenRead(filePath); _syncResource = syncResource; } public void Dispose() { if (_disposed) return; _fileStream.Dispose(); _syncResource.Dispose(); _disposed = true; GC.SuppressFinalize(this); } public async ValueTask DisposeAsync() { if (_disposed) return; await _fileStream.DisposeAsync(); _syncResource.Dispose(); _disposed = true; GC.SuppressFinalize(this); } }

In this example, Dispose() handles both resources synchronously, while DisposeAsync() uses FileStream.DisposeAsync() for the asynchronous resource and then disposes the synchronous resource. Because both methods check _disposed, they can be called safely more than once.

Compatibility and Language Version Requirements

await using requires C# 8.0 or later. The IAsyncDisposable interface is part of .NET Standard 2.1, so it is available in .NET Core 3.0 and all later .NET versions. For older targets such as .NET Framework, you may need to use the Microsoft.Bcl.AsyncInterfaces package or rely on the synchronous using instead.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.