Skip to content

Runtime async: superfluous thread pool post before SynchronizationContext.Post when awaiting Task with multiple awaiters or RunContinuationsAsynchronously #137351

Description

@timr-github

Description. This is a behaviour and cost difference from compiler-generated state machines, not a correctness bug: SynchronizationContext.Post
is asynchronous by contract and nothing promises which thread calls it. With <Features>runtime-async=on</Features> (.NET 11.0.0, CoreCLR JIT and
NativeAOT, osx-arm64), an async method that awaits a Task coming straight from a call (await tcs.Task, await GetTask(),
await tcs.Task.ConfigureAwait(true), and in Release also var t = tcs.Task; await t;) under a custom SynchronizationContext has its continuation
queued to the thread pool first, and Post is then called from a pool thread, when the task does not run that continuation inline: the second and later
await continuations of a task, and every continuation of a task created with RunContinuationsAsynchronously. State machines (and runtime async when the
awaited task is a stored value: a field or a parameter) call Post directly from the completing thread, inside SetResult.

Effects: each such resume costs one extra thread-pool work item (measured below: exactly one per hop), and Post now happens after SetResult returned, at
a timing-dependent moment and in a timing-dependent order. Hosts that drain their context's queue once per frame (games, UI loops) therefore resume these
continuations in a frame that depends on thread timing, where state machines resume them all in the frame that completed the task. Is the hop intended for
this path? If not, could the transparent await post to the caller's context directly, as the Suspend path and state machines do?

Repro (console app, net11.0, <ImplicitUsings>enable</ImplicitUsings>, <Nullable>enable</Nullable>, <Features>runtime-async=on</Features>, Release):

using System.Threading;
using System.Threading.Tasks;

int main = Environment.CurrentManagedThreadId;
var tcs = new TaskCompletionSource();
for (int i = 0; i < 3; i++)
{
    SynchronizationContext.SetSynchronizationContext(new Ctx($"awaiter {i}", main));
    _ = Awaiter(tcs);
}
SynchronizationContext.SetSynchronizationContext(null);
tcs.SetResult();
Console.WriteLine("SetResult returned");
Thread.Sleep(200);

static async Task Awaiter(TaskCompletionSource tcs) => await tcs.Task;

sealed class Ctx(string name, int main) : SynchronizationContext
{
    public override void Post(SendOrPostCallback d, object? state) =>
        Console.WriteLine($"{name}: Post from {(Environment.CurrentManagedThreadId == main ? "the completing thread" : "a thread-pool thread")}");
}

Without runtime-async=on (5 of 5 runs):

awaiter 1: Post from the completing thread
awaiter 2: Post from the completing thread
awaiter 0: Post from the completing thread
SetResult returned

With runtime-async=on (2 of 5 runs; the order of the pool-thread lines and of SetResult returned varies from run to run):

awaiter 1: Post from a thread-pool thread
awaiter 2: Post from a thread-pool thread
awaiter 0: Post from the completing thread
SetResult returned
awaiter 0: Post from the completing thread
SetResult returned
awaiter 2: Post from a thread-pool thread
awaiter 1: Post from a thread-pool thread

Matrix (same harness, 200 runs a cell; "sync" = Post from the completing thread inside SetResult in all 200 runs, "hop" = Post from a pool thread in
all 200; "+N" = thread-pool work items completed per run). CoreCLR JIT and NativeAOT give identical tables. Without runtime-async=on every cell is "sync, +0".

Await shape, runtime async on 3 awaiters 1 awaiter, RCA 3 awaiters, RCA
await tcs.Task 1st sync, 2nd + 3rd hop, +2 hop, +1 all hop, +3
await GetTask() (non-async, NoInlining, returns tcs.Task) 1st sync, 2nd + 3rd hop, +2 hop, +1 all hop, +3
await tcs.Task.ConfigureAwait(true) 1st sync, 2nd + 3rd hop, +2 hop, +1 all hop, +3
var t = tcs.Task; await t; Release 1st sync, 2nd + 3rd hop, +2 hop, +1 all hop, +3
var t = tcs.Task; await t; Debug sync, +0 sync, +0 sync, +0
Task t = s_field; await t; sync, +0 sync, +0 sync, +0
await s_field.ConfigureAwait(true) sync, +0 sync, +0 sync, +0
await Callee(s_field) (async Task Callee(Task t) => await t;) sync, +0 sync, +0 sync, +0

RCA = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously).

Analysis (dotnet/runtime release/11.0 at 0be7d8e; AsyncHelpers.CoreCLR.cs and RuntimeAsyncTaskContinuation.cs are in
src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/, which NativeAOT compiles too; AsyncHelpers.cs, Task.cs and TaskContinuation.cs are
under src/libraries/System.Private.CoreLib/src/System/):

  • Awaiting a stored task goes through AsyncHelpers.Await(Task) -> Suspend(task, ContinueOnCapturedContext) (AsyncHelpers.cs L148-153), which captures
    the context onto the task continuation (AsyncHelpers.CoreCLR.cs L386-389 -> CaptureContinuationContext L1454-1462: ContinueOnCapturedSynchronizationContext).
  • Awaiting a call's result calls the callee's async variant; for a Task-returning method that is a thunk ending in TransparentAwait (L689-704) ->
    TransparentSuspend(Task) (L633-655), which registers a RuntimeAsyncTaskContinuation without capturing any context flags; the caller's flags are on
    the caller's own continuation further along Next.
  • Task.RunContinuations (Task.cs L3620-3792): canInlineContinuations is false for RCA tasks (L3629-3631); in a list, the first await continuation runs
    with it and every later one gets Execute(canInline: false) (L3718-3747; L3728-3729).
  • RuntimeAsyncTaskContinuation.Execute(canInline: false) (RuntimeAsyncTaskContinuation.cs L27-42): with no flags it calls
    ThreadPool.UnsafeQueueUserWorkItemInternal(RuntimeAsyncTask, preferLocal: true) (L39). The pool thread runs DispatchContinuations (AsyncHelpers.CoreCLR.cs
    L934), resumes the thunk, reaches the caller's continuation and QueueContinuationFollowUpActionIfNecessary (L1036, L1207-1251) posts to its context
    from the pool thread (L1243).
  • With flags on the task continuation (the Suspend path), QueueIfNecessary(canInline: false) posts directly (RuntimeAsyncTaskContinuation.cs L66-88,
    Post at L81), like the state machines' SynchronizationContextAwaitTaskContinuation.Run(task, false) (TaskContinuation.cs L392-410, Post at L428).
  • The inline case (first continuation, no RCA) runs RuntimeAsyncTask.ExecuteDirectly on the completing thread (L33-35), and
    QueueContinuationFollowUpActionIfNecessary posts from there: hence "1st sync".

Possible direction (untested): HandleSuspended already looks along Next for the first continuation with context flags when it registers a
ValueTaskSourceContinuation (AsyncHelpers.CoreCLR.cs L855-880) and clears them there so the context is applied once. Doing the same for a transparent
RuntimeAsyncTaskContinuation in its TaskContinuation branch (L828-840), moving the caller's flags and context onto the task continuation, would let
Execute(canInline: false) post directly and leave the inline path as it is.

Workarounds we use: await a stored task (field or parameter) or an async wrapper that does; a custom awaiter that hooks the task with ContinueWith
on an inline scheduler and posts itself; or build that code without runtime async. ConfigureAwait(true) on a call's result does not avoid it.

Environment. SDK 11.0.100, Microsoft.NETCore.App 11.0.0, macOS 27 arm64, Release, CoreCLR JIT and NativeAOT (same result).

Activity

  1. added
    untriaged
    on Nov 11, 2026
  2. dotnet-policy-service commented on Nov 11, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-threading-tasks
    See info in area-owners.md if you want to be subscribed.

  3. Sergio0694 commented on Nov 12, 2026

    @Sergio0694
    Contributor

    This seems especially bad for Windows GUI apps. Having to go through a Dispatcher/DispatcherQueue every single time you await a task like this (which also means allocating a CCW for the continuation, plus the native callback object to pass to WinRT, etc.) seems like a ton of additional overhead in this specific scenario (especially given this involves creating a bunch of finalizable objects too for that CCW).

  4. changed the title [-]Runtime async: awaiting a Task returned by a call adds a thread-pool hop before SynchronizationContext.Post (differs from state machines)[/-] [+]Runtime async: superfluous thread pool post when before SynchronizationContext.Post when awaiting Task with multiple awaiters or RunContinuationsAsynchronously[/+] on Nov 12, 2026
  5. changed the title [-]Runtime async: superfluous thread pool post when before SynchronizationContext.Post when awaiting Task with multiple awaiters or RunContinuationsAsynchronously[/-] [+]Runtime async: superfluous thread pool post before `SynchronizationContext.Post` when awaiting Task with multiple awaiters or `RunContinuationsAsynchronously`[/+] on Nov 12, 2026
  6. jakobbotsch commented on Nov 12, 2026

    @jakobbotsch
    Member

    Note that this bug specifically happens only in cases where we believe we cannot inline continuations in Task.RunContinuations:

    • Awaiting TaskCompletionSource explicitly created with RunContinuationsAsynchronously
    • Multiple runtime async functions awaiting the same Task instance (the first will be posted directly, rest will first go to thread pool)
    • Not enough stack available (not actually clear to me if the async1 behavior that calls into arbitrary user code here is intended)
  7. timr-github commented on Nov 12, 2026

    @timr-github
    Author

    On the "not enough stack" case: I measured it with and without runtime async (.NET 11.0.0, Release, osx-arm64; CoreCLR JIT and NativeAOT give the same table; 200 runs per cell). One await tcs.Task (plain TaskCompletionSource, one awaiter) under a recording SynchronizationContext; a 256 KB thread completes the task, either straight away or after recursing until RuntimeHelpers.TryEnsureSufficientExecutionStack() returns false.

    Stack when SetResult runs Runtime async Compiler state machines
    Room left Post inside SetResult, 0 pool items Post inside SetResult, 0 pool items
    Nearly exhausted Post from a pool thread, 1 pool item Post inside SetResult, 0 pool items

    State machines never run the continuation inline here; they only call Post, which queues it and is asynchronous by contract. That keeps the stack safe and still queues the continuation before SetResult returns. Runtime async could do the same in all three no-inline cases (RunContinuationsAsynchronously, later awaiters, low stack): post to the captured context directly instead of going through the thread pool first. Hosts that drain their context once per frame would then resume these continuations in the frame that completed the task, as they do with state machines.

    Repro core:

    static async Task Awaiter(TaskCompletionSource tcs) => await tcs.Task;
    // SetSynchronizationContext(recordingCtx); var t = Awaiter(tcs); SetSynchronizationContext(null);
    // room:      tcs.SetResult();
    // exhausted: void Deep() { if (RuntimeHelpers.TryEnsureSufficientExecutionStack()) Deep(); else tcs.SetResult(); }
  8. jakobbotsch commented on Nov 12, 2026

    @jakobbotsch
    Member

    Post is a call into arbitrary user-defined code since it is an user-defined override of SynchronizationContext. Calling arbitrary user code in the constrained environment is precisely what the check is trying to avoid, since it is possible to hit the low stack-space cases under async in normal scenarios.

  9. timr-github commented on Nov 12, 2026

    @timr-github
    Author

    Thanks, that makes sense: the low-stack case avoiding a call into user code is reasonable, and I'm fine with the hop there.

    The other two cases are the ones that matter to us, and stack space isn't the reason inlining is off there: a task created with RunContinuationsAsynchronously, and the second and later awaiters of one task. In both, state machines already call Post directly from the completing thread (SynchronizationContextAwaitTaskContinuation.Run(task, canInlineContinuationTask: false)), so posting directly in runtime async wouldn't call user code anywhere state machines don't today. Could the transparent await capture the caller's context the way the Suspend path does, so those two cases post directly instead of going through the thread pool first?

    For hosts that drain their context once per frame (games, UI loops), that is the difference between resuming in the frame that completed the task and resuming in a timing-dependent frame, besides the extra work item per resume.

  10. jakobbotsch commented on Nov 12, 2026

    @jakobbotsch
    Member

    Yes, as I said above there is a bug here, I was just pointing out that I am unsure that the behavior of the third stack-check case is intended.

  11. timr-github commented on Nov 12, 2026

    @timr-github
    Author

    Got it, thanks, I misread that as being about runtime async. Agreed on the low-stack case. If it helps, we can try a fix on our side once there's a build: osx-arm64, iOS and Android, CoreCLR and NativeAOT, with the repro above plus our engine's frame-loop context.

  12. added this to the 12.0.0 milestone on Nov 12, 2026
  13. removed
    untriaged
    on Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions