skip to content

How should an unsealed C# class implement both IDisposable and IAsyncDisposable so either disposal path releases everything exactly once?

level: seniorimportance: should knowfreq 32%

answer

  1. a protected virtual async hook
  2. false, not true, afterwards
  3. suppress finalization on both paths
  4. same work, sync and async
  5. test the field for the async interface

basics

~10 s

Add a protected virtual ValueTask DisposeAsyncCore beside Dispose(bool). DisposeAsync awaits DisposeAsyncCore, then calls Dispose(false) and GC.SuppressFinalize; both paths do the same cleanup, check whether it already ran, and can safely run twice.

solid answer

~40 s

Keep the `Dispose(bool)` pattern and add `protected virtual ValueTask DisposeAsyncCore()`. `Dispose()` calls `Dispose(true)` and `GC.SuppressFinalize(this)`; `DisposeAsync()` awaits `DisposeAsyncCore()`, then calls `Dispose(false)` so only the unmanaged part runs, then `GC.SuppressFinalize(this)`. The language never calls both, so the type must make them equivalent: for a buffering publisher, both flush the buffer and close the connection, one with `WriteAsync` and `DisposeAsync`, the other with `Write` and `Dispose`. Each path nulls the fields it released and checks them first, so repeated or mixed calls are no-ops. For an owned field typed `IDisposable`, test `is IAsyncDisposable` and await it, else call `Dispose`. A derived class overrides `DisposeAsyncCore` and awaits the base version.

code

csharp · 31 lines
csharp
var w1 = new MemoryStream(); var w2 = new MemoryStream();
await using (var p = new QueuePublisher(w1)) p.Enqueue("async");
using (var p = new QueuePublisher(w2)) p.Enqueue("sync");
Console.WriteLine($"{w1.ToArray().Length} {w2.ToArray().Length}");
public class QueuePublisher(Stream connection) : IDisposable, IAsyncDisposable
{
    private readonly List<byte[]> _buffer = [];
    private Stream? _connection = connection;
    public void Enqueue(string m) => _buffer.Add(System.Text.Encoding.UTF8.GetBytes(m));
    public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); }
    public async ValueTask DisposeAsync()
    {
        await DisposeAsyncCore().ConfigureAwait(false);
        Dispose(disposing: false);
        GC.SuppressFinalize(this);
    }
    protected virtual void Dispose(bool disposing)
    {
        if (disposing && _connection is not null)
            foreach (var b in _buffer) _connection.Write(b);   // same flush, synchronous
        if (disposing) _connection?.Dispose();
        _connection = null;
    }
    protected virtual async ValueTask DisposeAsyncCore()
    {
        if (_connection is null) return;
        foreach (var b in _buffer) await _connection.WriteAsync(b).ConfigureAwait(false);
        await _connection.DisposeAsync().ConfigureAwait(false);
        _connection = null;
    }
}

go deeper

for a junior

Remember the member names: Dispose, DisposeAsync, the protected virtual DisposeAsyncCore, and that DisposeAsync ends with GC.SuppressFinalize.

for a middle

Explain why DisposeAsync calls Dispose(false) after DisposeAsyncCore, and why each path checks and clears its fields so a repeated or mixed call is harmless.

for a senior

Demonstrate that you make both paths do equivalent work with real synchronous and asynchronous APIs, cascade correctly into fields that may or may not be async, and keep the chain intact in subclasses.

for a principal

Weigh whether supporting both paths is worth the duplicated cleanup logic, versus offering only IAsyncDisposable and accepting that synchronous consumers cannot use the type.

## Why a type implements both A buffering message publisher is the classic case: it is used from asynchronous code, which wants to **await** the final flush, and from older synchronous code, which can only call `Dispose()`. The .NET guidance warns that a type with only `IAsyncDisposable` can leak when a consumer only calls `Dispose`, so the publisher implements both. The language does not tie the two methods together: `using` calls only `Dispose`, `await using` only `DisposeAsync`. **Consistency is the type's job.** ## The shape for an unsealed class The guidance for an unsealed class adds one member to the familiar `Dispose(bool)` pattern from the lesson on `IDisposable`: | Member | Role | |---|---| | `public void Dispose()` | Calls `Dispose(true)`, then `GC.SuppressFinalize(this)` | | `public async ValueTask DisposeAsync()` | Awaits `DisposeAsyncCore()`, then calls `Dispose(false)` and `GC.SuppressFinalize(this)` | | `protected virtual ValueTask DisposeAsyncCore()` | Asynchronously releases managed resources and cascades to owned async disposables | | `protected virtual void Dispose(bool disposing)` | Releases managed resources when `disposing` is true; unmanaged ones always | ```csharp public async ValueTask DisposeAsync() { await DisposeAsyncCore().ConfigureAwait(false); Dispose(disposing: false); GC.SuppressFinalize(this); } ``` Key points: - **`Dispose(false)`, not `Dispose(true)`**, after `DisposeAsyncCore`. The managed resources were already released asynchronously; passing `false` runs only the unmanaged part, which is what a finalizer would run, instead of releasing the managed part a second time synchronously. - **`GC.SuppressFinalize(this)`** appears in both public methods, because either one may be the path that ran. - **`DisposeAsyncCore` is `protected virtual`** so a derived class can override it, add its own asynchronous cleanup and then await `base.DisposeAsyncCore()`. It is a naming convention, not something the compiler looks for; `await using` only ever calls `DisposeAsync`. - A **`sealed`** class can skip `DisposeAsyncCore` and do the asynchronous cleanup directly in `DisposeAsync`. - `ConfigureAwait(false)` inside the dispose path is the usual library choice, since cleanup does not need the caller's context. ## Making the two paths equivalent For the publisher, consistent means **both paths flush the buffer and close the connection**: 1. `DisposeAsyncCore` writes the buffered messages with `WriteAsync`, then awaits the connection's `DisposeAsync`. 2. `Dispose(true)` writes the same messages with the synchronous `Write`, then calls the connection's `Dispose`. 3. Each path sets the connection field to `null`, and each checks it first, so a second call on either path does nothing. Calling `DisposeAsync` and then `Dispose` releases everything exactly once. The synchronous path should use real synchronous APIs. Implementing `Dispose` as `DisposeAsync().AsTask().GetAwaiter().GetResult()` blocks a thread on asynchronous I/O and can deadlock under a single-threaded synchronization context. ## Fields that may be only IDisposable An owned field typed as `IDisposable` might also implement `IAsyncDisposable`. `Stream`, `StreamWriter`, `Utf8JsonWriter` and `System.Threading.Timer` implement both; plenty of types implement only `IDisposable`. In `DisposeAsyncCore`, prefer the asynchronous path when it exists: ```csharp if (_inner is IAsyncDisposable asyncInner) await asyncInner.DisposeAsync().ConfigureAwait(false); else _inner?.Dispose(); _inner = null; ``` Casting straight to `IAsyncDisposable` would throw `InvalidCastException` for a synchronous-only type, and always calling `Dispose` would throw away the asynchronous flush that the inner type offers. ## A derived class A subclass that adds its own async resource overrides `DisposeAsyncCore`, releases its resource, then awaits `base.DisposeAsyncCore()`. It overrides `Dispose(bool)` the same way and calls `base.Dispose(disposing)`. CA2215's documented check covers a `Dispose` method calling the base `Dispose`; it says nothing about `DisposeAsyncCore`, so the asynchronous chain depends on review. ## Review checklist - `DisposeAsync` awaits `DisposeAsyncCore()`, then calls `Dispose(false)` and `GC.SuppressFinalize(this)`, in that order. - Every resource released in `Dispose(true)` is also released in `DisposeAsyncCore`, and the reverse. - Both paths check whether the work already happened and clear what they released, so `DisposeAsync` followed by `Dispose`, or two calls of either, does nothing extra. - Owned fields are disposed asynchronously when they implement `IAsyncDisposable`, synchronously otherwise; borrowed ones are left alone, as the lesson on `IDisposable` describes. - Overrides in derived classes await `base.DisposeAsyncCore()` and call `base.Dispose(disposing)`. - Unit tests dispose through both `using` and `await using` and assert the same observable result, such as every buffered message reaching the connection.

  • Why does DisposeAsync call Dispose(false) instead of Dispose(true)?
    `DisposeAsyncCore` has already released the managed resources asynchronously. `Dispose(true)` would release them again, synchronously; `Dispose(false)` runs only the unmanaged-resource part, the same path a finalizer takes, so nothing is released twice and nothing is skipped.
  • How should a derived class add its own asynchronous cleanup?
    Override `DisposeAsyncCore`, release its own resources, then `await base.DisposeAsyncCore()` so the base type's resources go too. It overrides `Dispose(bool)` in parallel and calls `base.Dispose(disposing)`. It does not reimplement `DisposeAsync`, which stays in the base class.
  • Can Dispose simply block on DisposeAsync to stay consistent?
    It compiles, but `DisposeAsync().AsTask().GetAwaiter().GetResult()` blocks a thread on asynchronous I/O and can deadlock when called on a single-threaded synchronization context. Consistent means doing the same work with synchronous APIs, such as `Stream.Write` and `Stream.Dispose`.

  • DisposeAsync should call Dispose(true) after DisposeAsyncCore to be safe
  • Only Dispose needs GC.SuppressFinalize; DisposeAsync can skip it
  • await using calls DisposeAsyncCore directly, so it must be public
  • The language calls both Dispose and DisposeAsync, so each can do half the work
  • Cast every owned field to IAsyncDisposable and await it