Repository navigation
Conversation
|
Azure Pipelines: Successfully started running 3 pipeline(s). 12 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
|
Tagging subscribers to this area: @agocke |
Co-authored-by: VSadov <[email protected]>
ResultsMatched Release CoreCLR builds, Linux x64, AMD EPYC 7763. Each operation includes registering awaiters, completing the task, and waiting for every continuation to finish.
Affected cases improved 2.8–5.4×. Repeating with reversed job order confirmed the improvements. Control timings varied between runs; their work-item counts and allocations remained effectively unchanged. Allocation savings include thread-local cache effects. Two launches per case, five warmup iterations and fifteen measured iterations of 500 ms. NativeAOT and macOS ARM64 were not benchmarked. Benchmark codeThe measured benchmark body is reproduced below; the runner is shortened, and the separate verification-only mode is omitted. Project<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net12.0</TargetFramework>
<NETCoreAppMaximumVersion>12.0</NETCoreAppMaximumVersion>
<Features>runtime-async=on</Features>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet"
Version="0.16.0-preview.2" />
</ItemGroup>
</Project>Program.csusing System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Toolchains.CoreRun;
// Arguments: before-corerun after-corerun [BenchmarkDotNet options]
var config = ManualConfig.Create(DefaultConfig.Instance)
.AddJob(
CreateJob("A-Before", args[0]).AsBaseline(),
CreateJob("B-After", args[1]));
BenchmarkSwitcher.FromAssembly(typeof(RuntimeAsyncDispatch).Assembly)
.Run(args[2..], config);
static Job CreateJob(string id, string coreRun)
{
return Job.Default
.WithId(id)
.WithToolchain(CoreRunToolchain.From(new CoreRunSettings
{
SourceCoreRun = new FileInfo(coreRun),
CliPath = new FileInfo(
"/home/runner/work/runtime/runtime/.dotnet/dotnet"),
TargetFrameworkMoniker = "net12.0",
DisplayName = id,
CreateCopy = true
}))
.WithCustomBuildConfiguration("Release")
.WithMsBuildArguments("/p:NETCoreAppMaximumVersion=12.0");
}
[MemoryDiagnoser]
[ThreadingDiagnoser]
public class RuntimeAsyncDispatch
{
private PumpContext _context = null!;
private Task[] _awaiters = null!;
private TaskCreationOptions _creationOptions;
[Params(1, 3)]
public int Awaiters { get; set; }
[Params(false, true)]
public bool RunContinuationsAsynchronously { get; set; }
[Params(true, false)]
public bool CaptureContext { get; set; }
public long PostCount => _context.PostCount;
[GlobalSetup]
public void Setup()
{
_context = new PumpContext();
_awaiters = new Task[Awaiters];
_creationOptions = RunContinuationsAsynchronously
? TaskCreationOptions.RunContinuationsAsynchronously
: TaskCreationOptions.None;
}
[GlobalCleanup]
public void Cleanup()
{
_context.Dispose();
}
[Benchmark]
public int RoundTrip()
{
var source = new TaskCompletionSource(_creationOptions);
SynchronizationContext? previous = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(_context);
for (int i = 0; i < _awaiters.Length; i++)
{
_awaiters[i] = AwaitSource(source, CaptureContext);
if (_awaiters[i].IsCompleted)
{
throw new InvalidOperationException(
"The awaiter did not suspend.");
}
}
SynchronizationContext.SetSynchronizationContext(null);
source.SetResult();
if (CaptureContext)
{
SynchronizationContext.SetSynchronizationContext(_context);
for (int i = 0; i < _awaiters.Length; i++)
{
_context.DispatchOne();
}
}
else
{
Task.WaitAll(_awaiters);
}
foreach (Task awaiter in _awaiters)
{
if (!awaiter.IsCompleted)
{
throw new InvalidOperationException(
"The round trip did not finish.");
}
awaiter.GetAwaiter().GetResult();
}
if (!_context.IsEmpty)
{
throw new InvalidOperationException(
"A context callback was left queued.");
}
return _awaiters.Length;
}
finally
{
SynchronizationContext.SetSynchronizationContext(previous);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static async Task AwaitSource(
TaskCompletionSource source, bool captureContext)
{
if (captureContext)
{
await source.Task;
}
else
{
await source.Task.ConfigureAwait(false);
}
}
private sealed class PumpContext : SynchronizationContext, IDisposable
{
private readonly BlockingCollection<
(SendOrPostCallback Callback, object? State)> _queue = new();
private long _postCount;
public long PostCount => Volatile.Read(ref _postCount);
public bool IsEmpty => _queue.Count == 0;
public override void Post(SendOrPostCallback callback, object? state)
{
Interlocked.Increment(ref _postCount);
_queue.Add((callback, state));
}
public void DispatchOne()
{
if (!_queue.TryTake(out var work, millisecondsTimeout: 30_000))
{
throw new TimeoutException(
"No continuation reached the context.");
}
work.Callback(work.State);
}
public void Dispose()
{
_queue.Dispose();
}
}
}Run the shortened runner with the two preserved runtime hosts: /home/runner/work/runtime/runtime/.dotnet/dotnet run \
--project /tmp/runtime-async-benchmark/RuntimeAsyncDispatchBench.csproj \
-c Release -p:NETCoreAppMaximumVersion=12.0 -- \
"$BEFORE_CORERUN" "$AFTER_CORERUN" \
--filter '*' \
--launchCount 2 \
--warmupCount 5 \
--iterationCount 15 \
--iterationTime 500 \
--exporters JSON CSV
|
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: jakobbotsch <[email protected]>
Co-authored-by: jakobbotsch <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
|
Both failures are tracked known issues and have nothing to do with the PR's changes. Build Analysis is green. The
The Neither failure is in CoreCLR async or SynchronizationContext code, which is what the PR changes. All the other build legs passed. |
There was a problem hiding this comment.
🔵 Needs a closer look
The low-stack fallback changes scheduler inlining policy, leaving safety, performance, and async1-parity tradeoffs unresolved pending maintainer judgment and runtime validation.
No open issues 🎉
1 resolved since last review
Review effort: Balanced
Co-authored-by: copilot-swe-agent[bot] <[email protected]>

With multiple awaiters or
RunContinuationsAsynchronously, transparent task awaits could queue to the thread pool merely to dispatch to a captured context—adding one redundant work item per affected resume.ConfigureAwait(false), and the pool fallback when stack space is insufficient for user-defined scheduling code.The affected cases were 2.8–5.4× faster, measuring the complete round trip—not just
SetResult.Captured synchronization context, per operation:
ConfigureAwait(false)controls retained the same work-item counts and effectively identical allocations. Their timing differences varied between runs; no consistent regression emerged.These were matched Release CoreCLR builds on Linux x64, EPYC 7763. Repeating with reversed job order confirmed the improvements. NativeAOT and macOS ARM64 were not benchmarked.
SynchronizationContext.Postwhen awaiting Task with multiple awaiters orRunContinuationsAsynchronously#137351