Repository navigation
Conversation
|
Azure Pipelines: Successfully started running 3 pipeline(s). 13 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
Contributor
|
Tagging subscribers to this area: @agocke |
Contributor
Author
|
@EgorBot -amd -arm -windows_x64 using System.Runtime.CompilerServices;
using System.Threading.Channels;
using BenchmarkDotNet.Attributes;
// Compiled with runtime-async=on, so every async method here is a runtime async method.
[MemoryDiagnoser]
public class RuntimeAsyncDispatch
{
private const int Ops = 1024; // multiple of 16 so FanOut16 runs exactly Ops chains
[Params(1, 10)]
public int Depth;
private Channel<int> _channel = null!;
private readonly TaskCompletionSource[] _fanOut = new TaskCompletionSource[16];
private readonly Task[] _fanOutTasks = new Task[16];
[GlobalSetup]
public void Setup()
{
// Single reader + synchronous continuations: ReadAsync returns an IValueTaskSource-backed
// ValueTask, and TryWrite resumes the suspended reader inline on this thread.
_channel = Channel.CreateUnbounded<int>(new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = true,
AllowSynchronousContinuations = true,
});
}
// A chain of `Depth` frames suspends on a pending Task, then resumes inline when it completes.
[Benchmark(OperationsPerInvoke = Ops)]
public void AwaitPendingTask()
{
for (int i = 0; i < Ops; i++)
{
var tcs = new TaskCompletionSource();
Task t = TaskChain(tcs.Task, Depth);
tcs.SetResult();
t.GetAwaiter().GetResult();
}
}
// Same, but the leaf awaits an IValueTaskSource-backed ValueTask.
[Benchmark(OperationsPerInvoke = Ops)]
public int AwaitPendingValueTask()
{
int sum = 0;
for (int i = 0; i < Ops; i++)
{
ValueTask<int> t = ValueTaskChain(Depth);
_channel.Writer.TryWrite(i);
sum += t.GetAwaiter().GetResult();
}
return sum;
}
// 16 chains suspended at the same time, then completed.
[Benchmark(OperationsPerInvoke = Ops)]
public void FanOut16()
{
for (int i = 0; i < Ops / 16; i++)
{
for (int j = 0; j < 16; j++)
{
_fanOut[j] = new TaskCompletionSource();
_fanOutTasks[j] = TaskChain(_fanOut[j].Task, Depth);
}
for (int j = 0; j < 16; j++)
{
_fanOut[j].SetResult();
}
Task.WaitAll(_fanOutTasks);
}
}
// Custom awaiter path (YieldAwaitable) still needs the continuation delegate: regression guard.
[Benchmark]
public async Task TaskYield()
{
await YieldChain(Depth);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static async Task TaskChain(Task pending, int depth)
{
if (depth <= 1)
{
await pending;
}
else
{
await TaskChain(pending, depth - 1);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private async ValueTask<int> ValueTaskChain(int depth)
{
if (depth <= 1)
{
return await _channel.Reader.ReadAsync();
}
return await ValueTaskChain(depth - 1);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static async Task YieldChain(int depth)
{
if (depth <= 1)
{
await Task.Yield();
}
else
{
await YieldChain(depth - 1);
}
}
} |
Contributor
Author
|
@EgorBot -amd -arm -windows_x64 --filter "AwaitPendingValueTask" "FanOut16" "TaskYield" --launchCount 3 using System.Runtime.CompilerServices;
using System.Threading.Channels;
using BenchmarkDotNet.Attributes;
// Compiled with runtime-async=on, so every async method here is a runtime async method.
[MemoryDiagnoser]
public class RuntimeAsyncDispatch
{
private const int Ops = 1024; // multiple of 16 so FanOut16 runs exactly Ops chains
[Params(1, 10)]
public int Depth;
private Channel<int> _channel = null!;
private readonly TaskCompletionSource[] _fanOut = new TaskCompletionSource[16];
private readonly Task[] _fanOutTasks = new Task[16];
[GlobalSetup]
public void Setup()
{
// Single reader + synchronous continuations: ReadAsync returns an IValueTaskSource-backed
// ValueTask, and TryWrite resumes the suspended reader inline on this thread.
_channel = Channel.CreateUnbounded<int>(new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = true,
AllowSynchronousContinuations = true,
});
}
// A chain of `Depth` frames suspends on a pending Task, then resumes inline when it completes.
[Benchmark(OperationsPerInvoke = Ops)]
public void AwaitPendingTask()
{
for (int i = 0; i < Ops; i++)
{
var tcs = new TaskCompletionSource();
Task t = TaskChain(tcs.Task, Depth);
tcs.SetResult();
t.GetAwaiter().GetResult();
}
}
// Same, but the leaf awaits an IValueTaskSource-backed ValueTask.
[Benchmark(OperationsPerInvoke = Ops)]
public int AwaitPendingValueTask()
{
int sum = 0;
for (int i = 0; i < Ops; i++)
{
ValueTask<int> t = ValueTaskChain(Depth);
_channel.Writer.TryWrite(i);
sum += t.GetAwaiter().GetResult();
}
return sum;
}
// 16 chains suspended at the same time, then completed.
[Benchmark(OperationsPerInvoke = Ops)]
public void FanOut16()
{
for (int i = 0; i < Ops / 16; i++)
{
for (int j = 0; j < 16; j++)
{
_fanOut[j] = new TaskCompletionSource();
_fanOutTasks[j] = TaskChain(_fanOut[j].Task, Depth);
}
for (int j = 0; j < 16; j++)
{
_fanOut[j].SetResult();
}
Task.WaitAll(_fanOutTasks);
}
}
// Custom awaiter path (YieldAwaitable) still needs the continuation delegate: regression guard.
[Benchmark]
public async Task TaskYield()
{
await YieldChain(Depth);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static async Task TaskChain(Task pending, int depth)
{
if (depth <= 1)
{
await pending;
}
else
{
await TaskChain(pending, depth - 1);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private async ValueTask<int> ValueTaskChain(int depth)
{
if (depth <= 1)
{
return await _channel.Reader.ReadAsync();
}
return await ValueTaskChain(depth - 1);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static async Task YieldChain(int depth)
{
if (depth <= 1)
{
await Task.Yield();
}
else
{
await YieldChain(depth - 1);
}
}
} |
This was referenced Oct 16, 2026
thomhurst
force-pushed
the
runtime-async-dispatch-alloc
branch
from
October 18, 2026 08:01
f8d63c0 to
a357043
Compare
thomhurst
force-pushed
the
runtime-async-dispatch-alloc
branch
from
October 19, 2026 20:26
a357043 to
8169bfd
Compare
Create the RuntimeAsyncTask continuation delegate lazily. It is only needed when handing the task to a custom awaiter, a notifier or a non-default TaskScheduler; Task and IValueTaskSource awaits resume without it. This saves one delegate allocation per suspended runtime async chain. Pass the thread cached in t_runtimeAsyncAwaitState to QueueContinuationFollowUpActionIfNecessary instead of re-reading Thread.CurrentThreadAssumedInitialized for every resumed frame.
thomhurst
force-pushed
the
runtime-async-dispatch-alloc
branch
from
October 24, 2026 15:23
8169bfd to
091a4fe
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Two small changes to the runtime async dispatcher in
AsyncHelpers.CoreCLR.cs.Changes
1. Create the
RuntimeAsyncTask<T>continuation delegate lazilyThe
RuntimeAsyncTask<T>constructor allocatedm_action = DispatchContinuationseagerly, which is one delegate (56 B measured) for every runtime async chain that suspends. The delegate is only used when the task is handed to:OnCompleted/UnsafeOnCompleted, e.g.Task.Yield()),INotifyCompletionnotifier,TaskScheduler(RuntimeAsyncTaskContinuation.QueueIfNecessary).The common paths (awaiting a
Taskor anIValueTaskSource-backedValueTask) never use it.GetContinuationAction()now creates the delegate on first use, which matches how the classic builder handlesMoveNextAction(m_action ??= new Action(MoveNext)).RuntimeAsyncTaskContinuationonly has the task as aTask, so it reaches the lazy getter through a new internalIRuntimeAsyncTaskinterface. That path is only taken for non-default task schedulers.2. Avoid a thread-static lookup per resumed frame
QueueContinuationFollowUpActionIfNecessaryreadThread.CurrentThreadAssumedInitializedon every resumed frame, although the dispatcher already holds the current thread int_runtimeAsyncAwaitState.CurrentThread. The dispatcher now passes that cached thread in, asRestoreInlinedFrameContextsalready does. ADebug.Assertchecks that the cached thread is the current thread.Benchmarks
The benchmark suspends a chain of
Depthruntime async frames on a pendingTaskCompletionSourcetask, then completes the task so the chain resumes inline on the same thread. Depth 1 isolates the per-chain cost (change 1). Depth 10 exercises the per-frame resume path (change 2). The project is compiled withruntime-async=on. A sanity check confirms that the suspended task is anAsyncHelpers+RuntimeAsyncTask<T>, and that theTask.Yieldand non-defaultTaskSchedulerpaths still work on every build.Benchmark code
All builds are local Release builds of the same commit (bc110ba). Only
System.Private.CoreLib.dll(ReadyToRun) differs between them. They were compared with BenchmarkDotNet 0.16.0-preview.2--corerun.To show each change on its own, each change was measured separately:
mainRun 1: baseline vs A vs B
Run 2: A vs B, 3 launches each (to check change 2)
Summary:
EgorBot (PR vs main)
EgorBot ran a wider set of scenarios (snippet):
AwaitPendingTask: a chain awaits a pendingTask(the case above).AwaitPendingValueTask: the leaf awaits anIValueTaskSource-backedValueTask(single-readerChannelwith synchronous continuations).FanOut16: 16 chains suspended at the same time, then completed.TaskYield: a custom awaiter, which still needs the delegate (regression guard).All scenarios ran at depth 1 and depth 10.
AwaitPendingValueTask+2%, LinuxFanOut16+1%, macOSTaskYield+5%.--launchCount 3(EgorBot/Benchmarks#656, Linux AMD Turin and macOS M2): none of the slowdowns reproduced. Every scenario was faster with the PR or the same as main.Rerun results (time with the PR divided by time on main; lower is better):
The
windows_azure_turinjob failed on both requests. The bot's own runtime build hitMSB3027because an MSBuild process held a lock onCrossgen2Tasks.dll, so no benchmarks ran there. The local numbers above are from Windows x64.Testing
src/tests/async(Release, x64, Windows): 146 passed, 0 failed.build.cmd clr.corelib+clr.nativecorelib -rc releasebuilds cleanly.Debug.Assertis active.Diagnostics impact
I checked the readers of
m_actionin this repo (including cDAC) and in dotnet/diagnostics:threadpoolonly readsm_actionfor work items whose type is exactlySystem.Threading.Tasks.Task, so it does not read it forRuntimeAsyncTask<T>.dumpasyncfollows continuation chains throughm_actiononly for wrapper and continuation objects.RuntimeAsyncTaskContinuationhas nom_actionfield, and the custom-awaiter path still gets the same delegate.dumpasync's description of aRuntimeAsyncTaskthat suspended on aTaskorValueTaskno longer has the{Void DispatchContinuations()}suffix.