Skip to content
← All posts
· Delta1 Labs GlassDecompilationC#async

How await using decompiles in C#

A finally block cannot contain an await, yet await using calls DisposeAsync from one. The compiler dissolves the finally into branches inside the async state machine. Here is the exact shape — the saved-exception field, the second ValueTaskAwaiter, the DisposeAsync call — and how Glass recovers the await using.

A finally block that contains await is impossible at the IL level. A protected region is a pair of metadata offsets that must bracket one contiguous run of instructions, and an await tears the method in two — MoveNext returns at the suspension point and re-enters later at a different state. There is no single range to protect. Yet await using exists, and its entire purpose is to call DisposeAsync from a finally. The compiler resolves the contradiction by dissolving the finally: it rewrites the disposal into ordinary branches woven into the state machine, so every path that leaves the guarded body runs the disposal inline first. Decompiling the result means recognizing that dissolved shape and reassembling the await using that produced it.

The real question

Here is the source we will recover:

async Task CopyAsync(Stream src)
{
    await using var dst = File.Create("out.bin");
    await src.CopyToAsync(dst);
}

Two awaits are in play, but only one is visible. src.CopyToAsync(dst) is the explicit one. The hidden one is dst.DisposeAsync(), scheduled to run when control leaves the using scope — whether the body completes, returns early, or throws. The compiler cannot express “await in a finally”, so it has to encode all three exit paths by hand. The question is: what does that hand-encoding look like, and how does a decompiler walk it back to one line of source?

What the compiler actually emits

Conceptually, await using first lowers to a plain try/finally:

FileStream dst = File.Create("out.bin");
try
{
    await src.CopyToAsync(dst);
}
finally
{
    if (dst != null)
        await dst.DisposeAsync();
}

But that await in the finally cannot survive to IL. The async rewriter takes a second pass and flattens it. The generated MoveNext carries extra state-machine fields to hold what a real finally would have held on the stack and in the exception machinery:

private sealed class <CopyAsync>d__0 : IAsyncStateMachine
{
    public int <>1__state;
    public AsyncTaskMethodBuilder <>t__builder;
    public Stream src;
    private FileStream <dst>5__1;          // the resource
    private object <>s__2;                  // captured body exception
    private TaskAwaiter <>u__1;            // CopyToAsync awaiter
    private ValueTaskAwaiter <>u__2;       // DisposeAsync awaiter
}

The two awaiter fields are the tell. <>u__1 parks the visible await; <>u__2 parks the disposal await — a ValueTaskAwaiter, because IAsyncDisposable.DisposeAsync() returns ValueTask. The object <>s__2 field is where a body exception is stashed so it can be rethrown after disposal has awaited to completion. No ordinary async method needs an object-typed field like this; it only appears when an exception has to outlive a suspension point.

The exit region of MoveNext, decompiled, reads like this:

object pendingException;
try
{
    // ... the awaited body: src.CopyToAsync(dst) ...
}
catch (object ex)        // captures everything the body can throw
{
    <>s__2 = ex;
}
FileStream dst = <dst>5__1;
if (dst != null)
{
    ValueTaskAwaiter awaiter = dst.DisposeAsync().GetAwaiter();
    if (!awaiter.IsCompleted)
    {
        <>1__state = 1;
        <>u__2 = awaiter;
        <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
        return;                      // suspend inside the "finally"
    }
    awaiter.GetResult();
}
pendingException = <>s__2;
if (pendingException != null)
{
    if (pendingException is Exception e)
        ExceptionDispatchInfo.Capture(e).Throw();   // rethrow, stack intact
}
<>s__2 = null;
<dst>5__1 = null;                    // unroot the resource

That is the whole trick. The disposal runs on every exit because it sits after the body unconditionally, not inside a protected region. The body’s exceptions are caught, held in <>s__2, and rethrown only once DisposeAsync has been awaited to its GetResult(). The ExceptionDispatchInfo.Capture(...).Throw() preserves the original stack trace so the rethrow is indistinguishable from a real finally. And because DisposeAsync can itself suspend, the whole disposal block is a second entry point into MoveNext, reached when <>1__state == 1.

In IL, the disposal await is the part worth seeing literally — the DisposeAsync call resolves against the IAsyncDisposable interface and hands back a ValueTask:

ldarg.0
ldfld      class [System.Private.CoreLib]System.IO.FileStream '<CopyAsync>d__0'::'<dst>5__1'
brfalse.s  IL_00e2
ldarg.0
ldfld      class [System.Private.CoreLib]System.IO.FileStream '<CopyAsync>d__0'::'<dst>5__1'
callvirt   instance valuetype [System.Private.CoreLib]System.Threading.Tasks.ValueTask [System.Private.CoreLib]System.IAsyncDisposable::DisposeAsync()
stloc.s    V_4
ldloca.s   V_4
call       instance valuetype [System.Private.CoreLib]System.Runtime.CompilerServices.ValueTaskAwaiter [System.Private.CoreLib]System.Threading.Tasks.ValueTask::GetAwaiter()

Note the callvirt targets System.IAsyncDisposable::DisposeAsync, not FileStream’s own method. The compiler always dispatches await using disposal through the interface slot — the same way using dispatches through IDisposable.Dispose — which is one of the signatures Glass keys on.

How Glass puts it back together

Glass does not pattern-match line by line; it matches the structure of the exit region against the known shape of asynchronous disposal.

State machine <CopyAsync>d__0<dst>5__1 : FileStream<>s__2 : object<>u__1 : TaskAwaiter<>u__2 : ValueTaskAwaitercatch(ex) => <>s__2 = exawait DisposeAsync(); rethrowGlass recogniserresource field disposed viaawaited IAsyncDisposable+ saved-exception field+ null-guard + unrootawait using vardst = File.Create(    "out.bin");The two awaiter fields, the object-typed saved-exception field, and the interface-dispatched DisposeAsynctogether are unambiguous: only await using generates all four at once in a method-exit region.
Glass matches the exit-region structure — not individual lines — to reconstruct the await using scope.

The recogniser asks four questions of the exit region:

  1. Is there a resource local or field that is null-checked and then disposed through IAsyncDisposable.DisposeAsync, with that call immediately awaited?
  2. Are the body’s exceptions captured into an object-typed compiler field rather than flowing through a real exception clause?
  3. Is the captured exception rethrown via ExceptionDispatchInfo after the disposal await, not before?
  4. Is the resource field nulled out in the epilogue?

When all four hold, Glass collapses the entire region — catch, saved-exception juggling, disposal await, rethrow, unroot — back into a single await using var dst = File.Create("out.bin"); and restores the body as its scope. The pendingException plumbing and the <>s__2/<>u__2 fields never appear in the output; they were only ever an encoding of a finally the IL could not hold.

Variations and where it breaks

A few shapes change the generated code without changing the recovery:

  • await using (var x = ...) with an explicit block vs. the declaration form produce the same region; Glass renders whichever reads cleaner, preferring the declaration form inside a method.
  • ConfigureAwait(false) on the disposal makes the disposal awaiter ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter and routes through ConfiguredAsyncDisposable. Glass tracks that variant and re-emits the .ConfigureAwait(false) on the recovered await using.
  • Multiple resources in nested await using scopes produce nested exit regions with one saved-exception field reused across levels; the recogniser peels them outermost-last.

Where it genuinely breaks: if an obfuscator has flattened the state machine’s control flow or renamed the synthesized fields so the <>s__N/<>u__N naming is gone, the structural match still works — it keys on types and call targets, not names — but a heavily rewritten dispatcher can split the disposal await across basic blocks in a way that defeats the single-region match. In that case Glass falls back to showing the raw state machine with the DisposeAsync await visible, which is still enough to read the intent. For your own assemblies with symbols, none of this arises; the recovery is exact.

Takeaway

await using is one of the clearest examples of the async rewriter paying a structural cost to honor a language guarantee: because a finally cannot cross a suspension point, the compiler dissolves it into a saved exception, a second awaiter, and an unconditional disposal block. A decompiler that only matched syntax would show you the wreckage. Glass matches the shape — resource, interface-dispatched DisposeAsync, captured-and-rethrown exception, unroot — and gives you back the one line you wrote. Try it on your own async code with Glass, free, and read the decompilation docs for the full state-machine recovery pipeline.

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.