In C#, when should a class implement IAsyncDisposable, and how does calling code make sure its DisposeAsync runs?
answer
- cleanup that waits on I/O
- flush a buffer before closing
- one method returning ValueTask
- try/finally with an awaited call
basics
~20 sImplement IAsyncDisposable when cleanup must await I/O, such as flushing buffered messages over a network. DisposeAsync returns a ValueTask, and callers use await using so the compiler awaits it when the scope ends, even after an exception.
solid answer
~40 s`IAsyncDisposable` declares one member, `ValueTask DisposeAsync()`. It earns its place when releasing the resource means waiting on I/O: a publisher flushing its buffer over a socket, a writer pushing buffered bytes to a file, a component waiting for its background loop to stop. Doing that in `Dispose()` would block a thread until the I/O finished. Callers consume it with `await using`, as a block or as a declaration scoped to the enclosing block; the compiler wraps the scope in `try`/`finally` and awaits `DisposeAsync()` in the `finally`, so it runs even when the body throws. If cleanup is in-memory or already synchronous, `IDisposable` is enough, and a type that still has synchronous callers should implement both interfaces.
code
csharp · 22 linesvar wire = new MemoryStream();
await using (var publisher = new BufferedPublisher(wire))
{
publisher.Enqueue("order-created");
publisher.Enqueue("order-paid");
}
Console.WriteLine($"flushed {wire.ToArray().Length} bytes");
sealed class BufferedPublisher(Stream connection) : IAsyncDisposable
{
private readonly List<string> _buffer = [];
public void Enqueue(string message) => _buffer.Add(message);
public async ValueTask DisposeAsync()
{
foreach (var message in _buffer)
await connection.WriteAsync(System.Text.Encoding.UTF8.GetBytes(message + "\n"));
_buffer.Clear();
await connection.DisposeAsync();
}
}go deeper
Recall that IAsyncDisposable has one method, DisposeAsync, returning ValueTask, and that await using is how you call it reliably. Give one concrete example of cleanup that needs to await I/O.
Explain that await using expands to try/finally with an awaited DisposeAsync, that it needs an async context (CS4033 otherwise), and why blocking on async cleanup inside Dispose is a poor substitute.
Show you weigh whether a type needs async cleanup at all, and that you check who disposes it: if synchronous call sites or IDisposable-only helpers exist, you implement both interfaces so nothing leaks.
Frame it as an API contract decision: adding IAsyncDisposable pushes callers toward async code, and leaving out IDisposable can strand synchronous consumers, so the choice follows from who will own and release the type.
## What the interface is `System.IAsyncDisposable` is a one-member interface that arrived alongside C# 8: ```csharp public interface IAsyncDisposable { ValueTask DisposeAsync(); } ``` It is the asynchronous twin of `IDisposable`. **`DisposeAsync`** takes no parameters and returns a **`ValueTask`**, so an implementation whose cleanup finishes synchronously can complete without allocating a `Task`. The call is something the caller awaits; the garbage collector never calls it, and a finalizer cannot await it. ## When cleanup needs to be asynchronous Add `IAsyncDisposable` when releasing the resource means **waiting on I/O** that has an asynchronous API. Typical cases: - a message publisher that buffers messages and must **flush them over the network** before the connection closes; - a writer that holds buffered bytes and must push them to a file or socket (`StreamWriter`, `FileStream` and `Utf8JsonWriter` all declare their own `DisposeAsync` for this reason); - a component that owns a background loop and must **await that loop's completion** before it can release shared state; - a wrapper that owns another object which itself implements `IAsyncDisposable`, so its own disposal has to cascade asynchronously. Doing any of this inside `Dispose()` forces a choice between skipping the work and blocking the calling thread until the I/O finishes. Blocking ties up a thread, and on a single-threaded synchronization context it can deadlock; the lesson on synchronization contexts covers that mechanism. ## When `IDisposable` alone is enough `IAsyncDisposable` is not a newer replacement for `IDisposable`; it is an extra contract for a specific kind of cleanup. - Cleanup that is purely in memory or calls only synchronous APIs, such as cancelling and disposing a `CancellationTokenSource` (which implements `IDisposable` but not `IAsyncDisposable`), gains nothing from a `DisposeAsync`. - A type that is never awaited by its callers would force them into `async` methods for no benefit. - A `DisposeAsync` with nothing to await is just a synchronous method wearing an asynchronous signature. ## Consuming it: `await using` Callers make sure `DisposeAsync` runs with **`await using`**, in either form: 1. the statement form, `await using (var p = new Publisher()) { ... }`, scoped to its block; 2. the declaration form, `await using var p = new Publisher();`, scoped to the end of the enclosing block. The compiler wraps the scope in `try`/`finally` and awaits `DisposeAsync()` in the `finally`, so the cleanup is awaited whether the block completes normally, returns early or throws. `await using` is an `await`, so it is allowed only where `await` is: inside an `async` method or lambda, or in top-level statements. In a synchronous method the SDK reports **CS4033**. ## Keeping synchronous callers in mind The .NET guidance on `DisposeAsync` warns that a type implementing `IAsyncDisposable` but not `IDisposable` can leak: code that only knows `IDisposable`, such as an older synchronous call site or a helper that disposes anything castable to `IDisposable`, never calls `DisposeAsync`. If such callers exist, implement both interfaces and make both paths release the same things. If no synchronous release is possible, `IAsyncDisposable` alone is acceptable, and the compiler then rejects a plain `using` on the type. | Cleanup work | Interface to implement | |---|---| | In-memory or synchronous-only release | `IDisposable` | | Awaitable I/O, all callers asynchronous | `IAsyncDisposable` | | Awaitable I/O, some callers synchronous | Both, kept consistent | ## Mistakes interviewers listen for - **Adding `IAsyncDisposable` everywhere.** It is justified by cleanup that awaits something, not by a codebase being mostly asynchronous. - **Forgetting the `await`.** Calling `publisher.DisposeAsync();` without awaiting it starts the cleanup and moves on; the flush may still be running, or may have failed silently, when the method returns. `await using` cannot forget. - **Disposing manually without `finally`.** Writing `await publisher.DisposeAsync();` as the last line of a method skips it whenever an earlier line throws. - **Expecting a finalizer to save you.** A finalizer cannot await anything, and touching other managed objects such as the connection from a finalizer is unsafe, so it cannot be relied on to flush buffered messages. - **Blocking in `Dispose` instead.** A synchronous `Dispose` that waits on asynchronous I/O works in a console test and stalls or deadlocks under a UI or other single-threaded context.
- Why does DisposeAsync return ValueTask rather than Task?Many implementations finish synchronously, for example when there is nothing left to flush or the object was already disposed. A `ValueTask` can represent that completed result without allocating a `Task` object, so the common fast path costs nothing extra. The caller just awaits it once, which `await using` does for you.
- What happens if the body of an await using block throws?The compiler places the `DisposeAsync()` call in a `finally`, so it is still awaited before the exception leaves the block. The exception then continues to propagate. If `DisposeAsync` itself throws during that unwinding, its exception replaces the original one, just as with a throwing `Dispose` in a plain `using`.
Closing a shop that has a queue at the till: you cannot just lock the door (synchronous dispose), you serve the waiting customers first and lock up when the last one leaves. await using is the manager who waits for that before going home.
- Every disposable class should implement IAsyncDisposable because async is always better
- The garbage collector calls DisposeAsync when the object is collected
- Dispose can just call DisposeAsync().GetAwaiter().GetResult() with no cost
- await using works inside any method, async or not
- DisposeAsync is skipped when the await using body throws