Skip to content

Avoid redundant thread-pool hops in runtime async context dispatch - #137450

Open
VSadov with Copilot wants to merge 7 commits into
mainfrom
copilot/fix-runtime-async-thread-pool-issue
Open

VSadov with Copilot wants to merge 7 commits into
mainfrom
copilot/fix-runtime-async-thread-pool-issue

Conversation

Copilot AI commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • Dispatch: Transfer captured synchronization-context or scheduler flags from the first flagged caller continuation to the task continuation, applying the context once.
  • Safety: Preserve inline execution, ConfigureAwait(false), and the pool fallback when stack space is insufficient for user-defined scheduling code.
  • Coverage: Add context/scheduler regression cases for await shapes, multiple awaiters, RCA, execution-context preservation, duplicate dispatch, and low-stack fallback.

The affected cases were 2.8–5.4× faster, measuring the complete round trip—not just SetResult.

Captured synchronization context, per operation:

Awaiters RCA Before → after Speedup Allocations Pool work items
1 Off 245 → 244 ns Unchanged 272 → 272 B 0 → 0
3 Off 1,989 → 713 ns 2.8× 1,112 → 872 B 2 → 0
1 On 1,244 → 230 ns 5.4× 551 → 272 B 1 → 0
3 On 2,403 → 701 ns 3.4× 1,195 → 872 B 3 → 0

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.

@azure-pipelines

azure-pipelines Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
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.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @agocke
See info in area-owners.md if you want to be subscribed.

Copilot AI changed the title [WIP] Fix superfluous thread pool post in runtime async Avoid redundant thread-pool hops in runtime async context dispatch Nov 12, 2026
Copilot AI requested a review from VSadov November 12, 2026 20:29
@VSadov

VSadov commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Results

Matched Release CoreCLR builds, Linux x64, AMD EPYC 7763. Each operation includes registering awaiters, completing the task, and waiting for every continuation to finish.

Capture context Awaiters RCA Time ns, before → after Bytes/op Pool items/op
Yes 1 Off 245 → 244 272 → 272 0 → 0
Yes 3 Off 1,989 → 713 1,112 → 872 2 → 0
Yes 1 On 1,244 → 230 551 → 272 1 → 0
Yes 3 On 2,403 → 701 1,195 → 872 3 → 0
No 1 Off 152 → 150 272 → 272 0 → 0
No 3 Off 1,627 → 1,673 991 → 992 2 → 2
No 1 On 863 → 800 447 → 447 1 → 1
No 3 On 1,719 → 1,642 1,064 → 1,064 3 → 3

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 code

The 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.cs

using 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

MemoryDiagnoser measures process-wide allocations, including pool threads. ThreadingDiagnoser reports completed pool work items per operation. The context and task-slot array are reused; each measured operation creates its own incomplete task and awaits it.

@VSadov
VSadov requested a balanced review from Copilot November 13, 2026 00:58
@VSadov
VSadov marked this pull request as ready for review November 13, 2026 01:05

This comment was marked as resolved.

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
@VSadov

VSadov commented Nov 17, 2026

Copy link
Copy Markdown
Member

Both failures are tracked known issues and have nothing to do with the PR's changes. Build Analysis is green.

The runtime build had 2 test failures out of about 1.47M tests:

  1. iOS.Device.ExportManagedSymbols.Test.WorkItemExecution: the iOS device package install failed (XHarness/devicectl). This matches open Known Build Error #123796.
  2. System.Net.Quic.Tests.MsQuicTests.ConnectWithCertificateForDifferentName_Throws: the QUIC handshake timed out. This matches open Known Build Error #133645.

The runtime (Build Monitor Helix Jobs) check also failed. It is most likely just reporting those same Helix test failures. I couldn't open its log to confirm, because Azure DevOps isn't reachable from this environment.

Neither failure is in CoreCLR async or SynchronizationContext code, which is what the PR changes. All the other build legs passed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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]>
Copilot AI requested a review from VSadov November 18, 2026 21:34

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

5 participants