skip to content

In C# library code, what does `await using var p = new Publisher().ConfigureAwait(false);` declare, and how should it be written instead?

level: middleimportance: nice to knowfreq 22%

answer

  1. the variable's type changes
  2. a struct from CompilerServices
  3. keep the resource in its own local
  4. only the dispose await is configured

basics

~10 s

It declares p as a ConfiguredAsyncDisposable, not a Publisher, so p.Publish fails with CS1061. Store the publisher in its own variable, then write await using (publisher.ConfigureAwait(false)); that configures only the final DisposeAsync await.

solid answer

~40 s

`ConfigureAwait(bool)` on an `IAsyncDisposable` is an extension in `TaskAsyncEnumerableExtensions` that returns `ConfiguredAsyncDisposable`, a struct whose only declared public member is a `DisposeAsync()` returning `ConfiguredValueTaskAwaitable`. `await using` accepts it by pattern, but in the declaration form the variable takes the wrapper's type, so `p` has no `Publish` method (CS1061) and the publisher has no usable name. Write `var publisher = new Publisher();` and then `await using (publisher.ConfigureAwait(false)) { ... }` or `await using var scope = publisher.ConfigureAwait(false);`. Only the disposal await is configured; awaits in the body need their own `ConfigureAwait(false)`. Keep each wrapper right after its own resource so a later constructor that throws cannot strand an unprotected object.

code

csharp · 23 lines
csharp
var publisher = new Publisher();
await using (publisher.ConfigureAwait(false))
{
    await publisher.SendAsync("order-created");   // not configured by the line above
}
Console.WriteLine($"disposed: {publisher.Disposed}");

sealed class Publisher : IAsyncDisposable
{
    public bool Disposed { get; private set; }

    public async Task SendAsync(string message)
    {
        await Task.Yield();
        Console.WriteLine($"sent {message}");
    }

    public async ValueTask DisposeAsync()
    {
        await Task.Yield();
        Disposed = true;
    }
}

go deeper

for a junior

Recall that ConfigureAwait(false) can be applied to an await using resource, and that it changes how the final DisposeAsync is awaited.

for a middle

Explain that the expression returns ConfiguredAsyncDisposable, so the declared variable loses the resource's members (CS1061), and show the two-variable fix.

for a senior

Point out that only the disposal await is configured, and that splitting creation from await using must not leave a window where a second constructor's exception strands the first resource.

for a principal

Treat it as part of a library's ConfigureAwait convention: decide whether disposal awaits follow the same rule as other awaits, and whether CA2007 enforces it.

## What the expression produces `ConfigureAwait(bool)` on an `IAsyncDisposable` is an extension method in `System.Threading.Tasks.TaskAsyncEnumerableExtensions`: ```csharp public static ConfiguredAsyncDisposable ConfigureAwait(this IAsyncDisposable source, bool continueOnCapturedContext) ``` It returns a **`ConfiguredAsyncDisposable`**, a `readonly struct` in `System.Runtime.CompilerServices`. That struct does **not** implement `IAsyncDisposable`. It declares one public method: ```csharp public ConfiguredValueTaskAwaitable DisposeAsync() => _source.DisposeAsync().ConfigureAwait(_continueOnCapturedContext); ``` `await using` accepts it through the **pattern-based** lookup: the compiler finds an accessible `DisposeAsync()` whose result is awaitable. ## The trap in the declaration form In `await using var p = new Publisher().ConfigureAwait(false);`, the variable `p` has the type of the whole initializer, so **`p` is a `ConfiguredAsyncDisposable`, not a `Publisher`**. Calling `p.Publish(...)` fails with **CS1061** ("'ConfiguredAsyncDisposable' does not contain a definition for 'Publish'..."), and the `Publisher` reference itself is not stored in any variable you can use. The fix keeps two names: 1. Create the resource into its own local: `var publisher = new Publisher();` 2. Hand the configured wrapper to `await using`: `await using (publisher.ConfigureAwait(false)) { ... }`, or `await using var scope = publisher.ConfigureAwait(false);`. 3. Use `publisher` inside the scope; the wrapper only governs how its disposal is awaited. ## What it configures, and what it does not The wrapper changes exactly **one await: the `DisposeAsync()` at the end of the scope**. - The awaits in the body, such as `await publisher.SendAsync(...)`, are not affected; each needs its own `ConfigureAwait(false)` if you want it. - `ConfigureAwait(false)` means the continuation after disposal does not have to resume on the captured synchronization context or task scheduler; with neither present, as in a console app, it changes nothing observable. The lesson on synchronization contexts covers that mechanism. - Analyzer rule **CA2007** ("Consider calling ConfigureAwait on the awaited task") flags an `await using` without it, which is why library code that enables CA2007 writes this form. The rule is not enabled by default. ## The gap between creating and protecting Splitting creation from `await using` opens a short window where the object exists but no `finally` protects it: | Code shape | If something throws before the `await using` line | |---|---| | `await using var p = new Publisher();` | Nothing to dispose: `p` is assigned only after construction succeeds | | `var p = new Publisher(); await using (p.ConfigureAwait(false))` | Only the `ConfigureAwait` call runs in between, and it just wraps the reference in a struct | | `var a = new A(); var b = new B();` then two `await using` lines | If `B`'s constructor throws, `a` was created and is never disposed | The .NET docs call the last shape **stacked usings** and recommend against it. Keep each `ConfigureAwait` wrapper on the line right after its own resource, or nest the blocks, so every resource is covered before the next one is created. ## When to bother In application code with no synchronization context, plain `await using` is fine. In a library that may run under a UI or other single-threaded context and that already follows a `ConfigureAwait(false)` convention, use the two-variable form so the disposal await follows the same rule as every other await in the method. ## Checklist for library code - Create the resource into a named local, then pass `resource.ConfigureAwait(false)` to `await using` on the very next line. - Use the resource's own variable in the body; never the wrapper. - Add `ConfigureAwait(false)` to each await in the body separately; the disposal wrapper does not cover them. - With several resources, repeat the pair per resource (create, then wrap), or nest the blocks, instead of creating all of them first. - If the project enables CA2007, expect it to flag any `await using` written without the wrapper.

  • Does ConfigureAwait(false) on await using affect the awaits inside the block?
    No. `ConfiguredAsyncDisposable.DisposeAsync()` simply returns `_source.DisposeAsync().ConfigureAwait(false)`, so only the await the compiler emits at the end of the scope is configured. Each await in the body, such as `await publisher.SendAsync(...)`, keeps its own behaviour unless you configure it too.
  • Why would a library write this form at all?
    Analyzer rule CA2007 flags an `await using` without `ConfigureAwait`, and a library that may run under a UI or other single-threaded synchronization context usually applies `ConfigureAwait(false)` to every await, the disposal one included. In application code with no synchronization context or custom task scheduler it changes nothing observable.

  • await using var p = x.ConfigureAwait(false) still lets you call x's methods on p
  • ConfigureAwait(false) on await using configures every await inside the block
  • ConfiguredAsyncDisposable implements IAsyncDisposable
  • Creating several resources first and wrapping them afterwards is just as safe