IAsyncDisposable and await using
IAsyncDisposable
Some resources close with an operation that has to wait: a network stream that flushes its last bytes, a connection that sends a goodbye. Blocking a thread for that wait is what IAsyncDisposable avoids. It declares one method, DisposeAsync, which returns a ValueTask:
await using (var first = new AsyncResource("first"))
{
await first.UseAsync();
}
Console.WriteLine("after block");
var second = new AsyncResource("second");
await second.UseAsync();
await second.DisposeAsync();
Console.WriteLine("done");
class AsyncResource(string name) : IAsyncDisposable
{
public async Task UseAsync()
{
await Task.Delay(10);
Console.WriteLine($"using {name}");
}
public async ValueTask DisposeAsync()
{
await Task.Yield();
Console.WriteLine($"dispose {name}");
}
}
dotnet run
using first
dispose first
after block
using second
dispose second
done
The order matches the synchronous lesson exactly: the block closes at its brace, the second resource was closed by hand, and the program ends with done. What changed is that the wait inside DisposeAsync did not hold a thread: the await Task.Yield() gave it back to the pool.
await using
- await using (var x = ...) { ... } is the block form, and await using var x = ...; is the declaration form; both call DisposeAsync and await it.
- The enclosing method must be async. A top-level program may contain await, which is why the programs on this page are written that way.
- DisposeAsync returns ValueTask rather than Task so that a resource which has nothing to wait for can complete without an allocation.
- A type may implement both interfaces; using and await using then choose the method each one needs.
An exception leaves the block
The guarantee is the same as with using: the disposal runs on every exit, and for the asynchronous form it is awaited before the exception continues:
try
{
await using var resource = new AsyncResource("inside");
await resource.UseAsync();
throw new InvalidOperationException("fail");
}
catch (Exception e)
{
Console.WriteLine($"caught {e.Message}");
}
Console.WriteLine("done");
class AsyncResource(string name) : IAsyncDisposable
{
public async Task UseAsync()
{
await Task.Delay(10);
Console.WriteLine($"using {name}");
}
public async ValueTask DisposeAsync()
{
await Task.Yield();
Console.WriteLine($"dispose {name}");
}
}
dotnet run
using inside
dispose inside
caught fail
done
dispose inside printed before the catch, so the resource was fully released while the exception travelled. If DisposeAsync itself throws, the runtime loses the original exception and reports the new one, so a disposal that may fail belongs in a try of its own when both errors matter.
A type with both interfaces
A resource that can close quickly and can also close asynchronously implements both, and the statement picks the one that matches:
var both = new Both();
await using (both)
{
Console.WriteLine("in block");
}
Console.WriteLine("done");
class Both : IDisposable, IAsyncDisposable
{
public void Dispose() => Console.WriteLine("sync dispose");
public ValueTask DisposeAsync()
{
Console.WriteLine("async dispose");
return ValueTask.CompletedTask;
}
}
dotnet run
in block
async dispose
done
await using called DisposeAsync and never touched Dispose. Swapping the two keywords would call the synchronous one instead, which is why a type that offers both must make the two agree: a caller may reach either according to the context it is in.
Exercises
- Make DisposeAsync of the first program take 50 milliseconds and time the block with a Stopwatch.
- Add a second await using to the first program and check the reverse order of disposal.
- Throw from DisposeAsync and see which exception the catch reports.
- Change ValueTask to Task in Both and check that nothing else has to change.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does IAsyncDisposable declare?
Answer
A DisposeAsync method that returns a ValueTask
The single member is DisposeAsync, and ValueTask keeps a completed disposal allocation-free.
-
What must the enclosing method be to use await using?
Answer
async
The disposal is awaited, so the method has to be able to await.
-
What does this program print?
await using (var r = new R("a")) { Console.WriteLine("body"); } class R(string n) : IAsyncDisposable { public ValueTask DisposeAsync() { Console.WriteLine("dispose " + n); return ValueTask.CompletedTask; } }Answer
body and then dispose a
The block body runs first and the disposal is awaited at the closing brace.
-
Why does DisposeAsync return ValueTask rather than Task?
Answer
A disposal with nothing to wait for completes without an allocation
ValueTask is a struct that avoids a heap object for the common synchronous completion.
-
What happens to the resource when the block throws?
Answer
It is disposed, and the disposal is awaited before the exception continues
The await using compiles to a try/finally that awaits the disposal.
-
A type implements both IDisposable and IAsyncDisposable. Which does await using call?
Answer
DisposeAsync
Each statement form calls the member it needs, so the two must agree.
-
What does this program print?
var b = new B(); using (b) { Console.WriteLine("block"); } class B : IDisposable, IAsyncDisposable { public void Dispose() => Console.WriteLine("sync"); public ValueTask DisposeAsync() => ValueTask.CompletedTask; }Answer
block and then sync
The synchronous using calls Dispose, which prints.
-
What does
await Task.Yield()do inside DisposeAsync?Answer
Gives the thread back and resumes on the pool
Yield posts the continuation and returns to the caller, which is what makes the method truly async.
-
Which resource needs IAsyncDisposable rather than IDisposable?
Answer
One whose close operation has to wait on I/O
The interface exists so the close can await instead of blocking a thread.
-
What does a disposal that throws do to an exception already leaving the block?
Answer
The new exception replaces the original one
A throw from the finally replaces the one in flight, which is why disposal must not fail silently.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev