C# Feature - await using
await using
Section titled “await using”await using disposes resources asynchronously when they implement IAsyncDisposable. It is the async counterpart to using.
Introduced In
Section titled “Introduced In”This feature was introduced in C# 8.0 (2019).
Why This Feature Exists
Section titled “Why This Feature Exists”Some resources need asynchronous cleanup, such as flushing buffers, completing network writes, or closing remote connections. A synchronous Dispose() call cannot express that work well. await using keeps disposal aligned with async control flow.
When To Use It
Section titled “When To Use It”- Use it for types that implement
IAsyncDisposable. - Use it in async methods that work with streams, transactions, writers, or SDK types that expose async cleanup.
- Prefer it over explicit
try/finallyplusDisposeAsync()when the scope is straightforward.
Before
Section titled “Before”var stream = new AsyncFileWriter(path);
try{ await stream.WriteAsync(payload);}finally{ await stream.DisposeAsync();}await using var stream = new AsyncFileWriter(path);await stream.WriteAsync(payload);Practical Example
Section titled “Practical Example”await using var transaction = await connection.BeginTransactionAsync();
await command.ExecuteNonQueryAsync();await transaction.CommitAsync();Common Pitfalls
Section titled “Common Pitfalls”await usingonly works forIAsyncDisposable; it is not interchangeable withIDisposable.- Disposal happens at the end of the current scope, so keep the scope as small as practical.
- If both sync and async disposal exist, prefer the async form inside async codepaths.
Version Notes
Section titled “Version Notes”- C# 8 introduced
await usingtogether with async disposal support.