Skip to main content

How to Dispose an Object Asynchronously with await using in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

await using (Notebook notes = new("notes")) { ... } calls notes.DisposeAsync() at the closing brace and waits until it has finished. It's the using statement for objects whose cleanup is slow work, such as saving to a disk.

Some objects need slow work to clean up, such as writing what's left to a file. They implement IAsyncDisposable, which Microsoft describes as: Provides a mechanism for releasing unmanaged resources asynchronously. The C# reference: Use the await using statement to correctly use an IAsyncDisposable instance. And: You use the await using statement to work with an asynchronously disposable object, that is, an object of a type that implements an IAsyncDisposable interface.

Syntax​

Syntax
await using (<Type> <name> = <new object>)
{
<statements>
}

await using <Type> <name> = <new object>;
PartWhat it is
await using (...) with a blockAn await using statement: DisposeAsync runs and is awaited when the block ends
await using <Type> <name> = <new object>;An await using declaration: DisposeAsync runs and is awaited at the end of the scope it's declared in
<Type>A type that implements IAsyncDisposable. Its one method, DisposeAsync, returns a ValueTask

Microsoft's guide on DisposeAsync: The public parameterless DisposeAsync() method is called implicitly in an await using statement.

The Example​

A console app called AwaitUsing has a Notebook class whose DisposeAsync takes half a second to save. It uses one notebook with an await using statement and one with an await using declaration.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n AwaitUsing
cd AwaitUsing
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/AwaitUsing/AwaitUsing.csproj:
Determining projects to restore...
Restored /Users/you/source/AwaitUsing/AwaitUsing.csproj (in 40 ms).
Restore succeeded.

dotnet new console -n AwaitUsing creates a folder named AwaitUsing with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or AwaitUsing.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the await using statement:

Program.cs (an await using statement)
// An await using statement: DisposeAsync runs at the closing brace, and the program waits for it.
await using (Notebook notes = new("notes"))
{
notes.Write("Buy milk");
}
Console.WriteLine("After the block");

notes lives inside the block. At the closing brace, C# calls notes.DisposeAsync() and waits for it before the next line runs.

Then the await using declaration:

Program.cs (an await using declaration)
// An await using declaration: DisposeAsync runs at the end of the scope, here the end of the program.
await using Notebook diary = new("diary");
diary.Write("A good day");
Console.WriteLine("End of the program");

With await using in front of a declaration, there's no block: diary is disposed at the end of the scope. With top-level statements, that's the end of the program.

And the class:

Program.cs (the class)
// IAsyncDisposable has one method, DisposeAsync, which returns a ValueTask.
class Notebook(string name) : IAsyncDisposable
{
public void Write(string text) => Console.WriteLine($"{name}: writing {text}");

public async ValueTask DisposeAsync()
{
Console.WriteLine($"{name}: saving...");
await Task.Delay(500); // Stands in for slow work, such as writing to a disk.
Console.WriteLine($"{name}: saved and closed");
}
}

IAsyncDisposable is the interface that await using needs. DisposeAsync is async and returns a ValueTask, so it can await slow work. Here Task.Delay(500) waits half a second in place of real saving.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
notes: writing Buy milk
notes: saving...
notes: saved and closed
After the block
diary: writing A good day
End of the program
diary: saving...
diary: saved and closed

macOS-style terminal window titled Terminal — AwaitUsing showing dotnet run printing notes: writing Buy milk, notes: saving..., notes: saved and closed, After the block, diary: writing A good day, End of the program, diary: saving... and diary: saved and closed

notes: saved and closed printed before After the block: the program waited for the half-second DisposeAsync before it went on. diary was disposed after End of the program, at the end of the scope, and the program waited for it too, so diary: saved and closed printed before the program exited.

The Complete File​

macOS-style code window titled Program.cs — AwaitUsing showing an await using statement with a block around the notes notebook, an await using declaration for the diary notebook, and a Notebook class that implements IAsyncDisposable with a Write method and an async DisposeAsync that waits half a second

Program.cs
// An await using statement: DisposeAsync runs at the closing brace, and the program waits for it.
await using (Notebook notes = new("notes"))
{
notes.Write("Buy milk");
}
Console.WriteLine("After the block");

// An await using declaration: DisposeAsync runs at the end of the scope, here the end of the program.
await using Notebook diary = new("diary");
diary.Write("A good day");
Console.WriteLine("End of the program");

// IAsyncDisposable has one method, DisposeAsync, which returns a ValueTask.
class Notebook(string name) : IAsyncDisposable
{
public void Write(string text) => Console.WriteLine($"{name}: writing {text}");

public async ValueTask DisposeAsync()
{
Console.WriteLine($"{name}: saving...");
await Task.Delay(500); // Stands in for slow work, such as writing to a disk.
Console.WriteLine($"{name}: saved and closed");
}
}

Without await, the Cleanup Doesn't Finish​

Calling DisposeAsync() yourself without await starts the cleanup but doesn't wait for it. This check uses the same Notebook class, calls DisposeAsync() without await, then prints a last line:

Calling DisposeAsync without await
Notebook notes = new("notes");
notes.Write("Buy milk");
notes.DisposeAsync();
Console.WriteLine("End of the program");

The build warned warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. The run:

Output
notes: writing Buy milk
notes: saving...
End of the program

notes: saved and closed never printed: the program ended while DisposeAsync was still waiting, so the save never finished.

Common Mistakes​

MistakeWhat happensDo this instead
using without await on an IAsyncDisposable typeerror CS8418: 'Notebook': type used in a using statement must implement 'System.IDisposable'. Did you mean 'await using' rather than 'using'?Write await using
await using on a type that only implements IDisposableerror CS8417: 'Pen': type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. Did you mean 'using' rather than 'await using'?Use a plain using for an IDisposable type
await using in a method that isn't asyncerror CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.Mark the method async, return Task and await the call: then notes: saved and closed printed before the caller's next line
Calling DisposeAsync() without awaitThe build warned CS4014, and the program ended before saved and closed printedUse await using

FAQ​

Does DisposeAsync run when an exception is thrown?​

Yes. With an exception thrown inside the block, the output was notes: saving..., notes: saved and closed and then the catch block's Caught: The pen ran out of ink. The cleanup finished before the exception reached the catch. The IAsyncDisposable reference: To make sure resources are released even in case of an exception, put the code that uses the IAsyncDisposable object into the using statement.

In which order are two await using declarations disposed?​

In reverse order. With first declared before second, a check printed second: saved and closed and then first: saved and closed. Microsoft's guide: This example runs in reverse order from which they were declared.

What if a class implements both IDisposable and IAsyncDisposable?​

await using calls DisposeAsync only. A check with both printed DisposeAsync ran, and Dispose ran never printed.

Conclusion​

Use await using for objects that implement IAsyncDisposable. C# calls DisposeAsync for you and waits for it to finish, at the closing brace of an await using statement or at the end of the scope for an await using declaration, even when an exception is thrown.

Additional Resources​