Codectionary / Developer documentation / C#

Await Cleanup with IAsyncDisposable

Use await using when releasing an owned resource can require asynchronous work.

Read the syntax

Use await using when releasing an owned resource can require asynchronous work.

Leaving it awaits DisposeAsync, including the asynchronous yield.

What it is and why to use it

Some resources need asynchronous work while being released, such as flushing buffered data. IAsyncDisposable exposes DisposeAsync, and await using awaits that cleanup when leaving its scope. It is not a faster form of every Dispose call. Use it when the resource genuinely offers an asynchronous lifetime contract.

How it works

DisposeAsync returns ValueTask. In a simple sealed type it can implement cleanup directly. Await using performs the cleanup on ordinary scope exit and during exception propagation. More complex inheritance or combined synchronous/asynchronous ownership requires the documented patterns. These examples simulate an asynchronous release and own no external service.

Common mistakes and limitations

Do not call DisposeAsync without awaiting it and assume cleanup has finished. Do not dispose resources another component owns. Cleanup itself can fail, so production error handling must consider both the body and disposal failure. Asynchronous disposal does not replace cancellation of ongoing operations.

Run the examples locally

These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.

Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.

C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.

Create and enter a project

dotnet new console -n CSharpExample --framework net10.0
cd CSharpExample

CSharpExample.csproj settings used for these examples

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>12.0</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>
</Project>

Build and run after saving one example in Program.cs

dotnet build
dotnet run --no-build

Continue learning

Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.

Syntax

await using (var resource = new AsyncLease()) { /* work */ }

Examples

Wait for release before continuing

Make the disposal ordering visible with a controlled scheduling yield.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

await using (var lease = new AsyncLease()) {
    Console.WriteLine("Working");
}
Console.WriteLine("After cleanup");
sealed class AsyncLease : IAsyncDisposable {
    public async ValueTask DisposeAsync() {
        await Task.Yield();
        Console.WriteLine("Released");
    }
}
  1. The scope owns the AsyncLease.
  2. Leaving it awaits DisposeAsync, including the asynchronous yield.
  3. After cleanup prints only after release completes; no sleep or external timing assumption is needed.
  4. Expected output: Working Released After cleanup
  5. Await owned asynchronous cleanup.

Clean up during a failure path

Observe disposal before an exception reaches the surrounding handler.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

try {
    await using var lease = new AsyncLease();
    throw new InvalidOperationException("Simulated body failure");
} catch (InvalidOperationException) { Console.WriteLine("Body failed"); }
sealed class AsyncLease : IAsyncDisposable {
    public ValueTask DisposeAsync() {
        Console.WriteLine("Released");
        return ValueTask.CompletedTask;
    }
}
  1. The body throws while the resource is still in its owning scope.
  2. Await using invokes the completed disposal operation before the catch is entered.
  3. The controlled body exception is then handled. This example’s cleanup does not fail; real disposal failures need an explicit policy too.
  4. Expected output: Released Body failed
  5. Await owned asynchronous cleanup.

Best practices

  • Await owned asynchronous cleanup.
  • Keep resource lifetime, cancellation and error reporting consistent.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading