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

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

  1. Make DisposeAsync of the first program take 50 milliseconds and time the block with a Stopwatch.
  2. Add a second await using to the first program and check the reverse order of disposal.
  3. Throw from DisposeAsync and see which exception the catch reports.
  4. 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.

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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