Repository navigation
Description
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 ->CaptureContinuationContextL1454-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 aRuntimeAsyncTaskContinuationwithout capturing any context flags; the caller's flags are on
the caller's own continuation further alongNext. Task.RunContinuations(Task.cs L3620-3792):canInlineContinuationsis false for RCA tasks (L3629-3631); in a list, the first await continuation runs
with it and every later one getsExecute(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 runsDispatchContinuations(AsyncHelpers.CoreCLR.cs
L934), resumes the thunk, reaches the caller's continuation andQueueContinuationFollowUpActionIfNecessary(L1036, L1207-1251) posts to its context
from the pool thread (L1243).- With flags on the task continuation (the
Suspendpath),QueueIfNecessary(canInline: false)posts directly (RuntimeAsyncTaskContinuation.cs L66-88,
Postat L81), like the state machines'SynchronizationContextAwaitTaskContinuation.Run(task, false)(TaskContinuation.cs L392-410,Postat L428). - The inline case (first continuation, no RCA) runs
RuntimeAsyncTask.ExecuteDirectlyon the completing thread (L33-35), and
QueueContinuationFollowUpActionIfNecessaryposts 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
dotnet-policy-service commentedon Nov 11, 2026
Tagging subscribers to this area: @dotnet/area-system-threading-tasks
See info in area-owners.md if you want to be subscribed.
Sergio0694 commentedon Nov 12, 2026
This seems especially bad for Windows GUI apps. Having to go through a
Dispatcher/DispatcherQueueevery 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).[-]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[/+][-]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`[/+]jakobbotsch commentedon Nov 12, 2026
Note that this bug specifically happens only in cases where we believe we cannot inline continuations in
Task.RunContinuations:TaskCompletionSourceexplicitly created withRunContinuationsAsynchronouslyTaskinstance (the first will be posted directly, rest will first go to thread pool)timr-github commentedon Nov 12, 2026
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 untilRuntimeHelpers.TryEnsureSufficientExecutionStack()returns false.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 beforeSetResultreturns. 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:
jakobbotsch commentedon Nov 12, 2026
Postis a call into arbitrary user-defined code since it is an user-defined override ofSynchronizationContext. 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.timr-github commentedon Nov 12, 2026
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
Postdirectly 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.
jakobbotsch commentedon Nov 12, 2026
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.
timr-github commentedon Nov 12, 2026
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.
fix: post the palette's hide check when the handler resumes