Skip to content

Restore current task tracking for runtime async dispatch - #132969

Merged
max-charlamb merged 1 commit into
dotnet:mainfrom
max-charlamb:max-charlamb/currenttask-dispatchcontinuation
Sep 1, 2026
Merged

max-charlamb merged 1 commit into
dotnet:mainfrom
max-charlamb:max-charlamb/currenttask-dispatchcontinuation

Conversation

@max-charlamb

@max-charlamb max-charlamb commented Aug 31, 2026

Copy link
Copy Markdown
Member

Summary

  • Restore AsyncDispatcherInfo.CurrentTask on the standard, non-instrumented DispatchContinuations path.
  • Make the current runtime async task available while its continuation chain is being dispatched.

This assignment was present before the instrumented and non-instrumented dispatch paths were separated in #126091.

Reasoning

Without this link, diagnostics tools cannot deterministically find the parent Task for a runtime async continuation chain in non-instrumented scenarios like crash dumps. While it is possible to use heuristics to link the tasks (trying to find the 'this' parameter of the DispatchContinuations caller) these do not work in all scenarios.

Given the very low overhead of writing this field, I believe it is valuable enough to re-add to the normal path.

Performance

Measured on Windows x64 under Hyper-V using BenchmarkDotNet with tiered compilation disabled. The benchmark performs 10,000 runtime-async suspensions and resumptions per invocation and compares separate baseline and changed Release testhosts.

Across 10 paired runs:

Runtime Mean
Baseline 65.857 ns
Changed 64.652 ns

The changed runtime measured 1.83% faster overall. The eight additional runs measured 1.24% faster, with the changed runtime faster in all eight. Because the change adds a store and shifts generated code layout, the apparent improvement should be treated as layout or environmental noise rather than a causal speedup. No performance regression was detected.

ReadyToRun code size for RuntimeAsyncTask<int>.DispatchContinuations increased by 7 bytes, from 1,488 to 1,495 bytes.

Testing

  • Release CoreCLR and libraries build
  • System.Runtime.Tests: 77,810 total, 0 failed, 88 skipped

Note

This pull request description was generated with GitHub Copilot.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 3514239f-5fe4-4f96-a3c8-0ef46470104e
@azure-pipelines

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

@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.

@max-charlamb

max-charlamb commented Aug 31, 2026

Copy link
Copy Markdown
Member Author

@EgorBot -windows_amd -windows_intel --envvars DOTNET_TieredCompilation:0

using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

BenchmarkSwitcher.FromAssembly(typeof(DispatchContinuationsBenchmarks).Assembly).Run(args);

public class DispatchContinuationsBenchmarks
{
    private const int IterationCount = 10_000_000;

    private static int s_value;

    private readonly NullAwaiter _awaiter = new();

    [IterationSetup]
    public void Warmup()
    {
        for (int i = 0; i < IterationCount; i++)
        {
            s_value += i;
        }
    }

    [Benchmark(OperationsPerInvoke = IterationCount)]
    public void DispatchContinuations()
    {
        Task task = RunContinuations(_awaiter);

        while (!task.IsCompleted)
        {
            _awaiter.Continue();
        }

        task.GetAwaiter().GetResult();
    }

    [RuntimeAsyncMethodGeneration(true)]
    private static async Task RunContinuations(NullAwaiter awaiter)
    {
        for (int i = 0; i < IterationCount; i++)
        {
            await awaiter;
        }
    }

    private sealed class NullAwaiter : ICriticalNotifyCompletion
    {
        private Action? _continuation;

        public NullAwaiter GetAwaiter() => this;

        public bool IsCompleted => false;

        public void Continue()
        {
            Action continuation = _continuation!;
            _continuation = null;
            continuation();
        }

        public void GetResult()
        {
        }

        public void OnCompleted(Action continuation) => throw new NotSupportedException();

        public void UnsafeOnCompleted(Action continuation) => _continuation = continuation;
    }
}

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
    internal sealed class RuntimeAsyncMethodGenerationAttribute(bool runtimeAsync) : Attribute
    {
        public bool RuntimeAsync => runtimeAsync;
    }
}

@max-charlamb
max-charlamb marked this pull request as ready for review August 31, 2026 14:59
Copilot AI lite review requested due to automatic review settings August 31, 2026 14:59
@azure-pipelines

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

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.

🟢 Approval recommended

Pull request overview

Restores population of AsyncDispatcherInfo.CurrentTask during the standard (non-instrumented) runtime-async continuation dispatch path in CoreCLR, so diagnostic tooling can reliably correlate nested runtime-async tasks with their continuation chains.

Changes:

  • Set asyncDispatcherInfo.CurrentTask = this; in the non-instrumented DispatchContinuations path to match the intent of the instrumented path (which sets it via RuntimeAsyncInstrumentationHelpers.ResumeRuntimeAsyncContext).
File summaries
File Description
src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncHelpers.CoreCLR.cs Restores AsyncDispatcherInfo.CurrentTask assignment for standard continuation dispatch to enable correct current-task tracking during dispatch.
Review details
  • Files reviewed: 1/1 changed files
  • Comments generated: 0
  • Review effort level: Lite

@max-charlamb
max-charlamb merged commit 98da697 into dotnet:main Sep 1, 2026
108 of 110 checks passed
@max-charlamb

Copy link
Copy Markdown
Member Author

/backport to release/11.0

@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Started backporting to release/11.0 (link to workflow run)

@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Sep 2, 2026
steveisok pushed a commit that referenced this pull request Sep 15, 2026
…ch (#133015)

Backport of #132969 to release/11.0

/cc @max-charlamb

## Customer Impact

- [ ] Customer reported
- [x] Found internally

On the standard, non-instrumented runtime-async dispatch path, `AsyncDispatcherInfo.CurrentTask` is not populated. As a result, diagnostics tools analyzing a live process or crash dump cannot deterministically associate a runtime-async continuation chain with its parent `Task`, which can produce incomplete or incorrect async task relationships. The issue affects .NET 11 runtime-async diagnostics when instrumentation is not enabled.

## Regression

- [x] Yes
- [ ] No

This regression was introduced by #126091, when the instrumented and non-instrumented continuation-dispatch paths were separated. Before that change, the shared dispatch path populated `CurrentTask`. The instrumented path still sets it through `RuntimeAsyncInstrumentationHelpers.ResumeRuntimeAsyncContext`, but the standard path lost the assignment.

## Testing

The corresponding fix on `main` built Release CoreCLR and libraries successfully and ran `System.Runtime.Tests` with 77,810 tests passing and 88 skipped. BenchmarkDotNet testing covered 10 million runtime-async suspension/resumption operations per invocation and found no performance regression across 10 paired runs.

No new test was added because this change restores diagnostic metadata held in stack-local dispatcher state rather than changing observable task execution behavior. The issue was missed when #126091 split the dispatch paths because existing tests validate runtime-async behavior and instrumentation, but do not inspect the non-instrumented stack state consumed by live-process and crash-dump diagnostics.

## Risk

Low. The change adds one pointer assignment to a stack-local `AsyncDispatcherInfo` immediately before continuation dispatch. It restores the behavior that existed before #126091 and matches the current-task tracking already performed by the instrumented path. It does not change control flow, public APIs, task completion semantics, or persisted data. Performance measurements detected no regression; ReadyToRun code size for `RuntimeAsyncTask<int>.DispatchContinuations` increased by 7 bytes, from 1,488 to 1,495 bytes.

**IMPORTANT**: If this backport is for a servicing release, please verify that:

- For .NET 8 and .NET 9: The PR target branch is `release/X.0-staging`, not `release/X.0`.
- For .NET 10+: The PR target branch is `release/X.0` (no `-staging` suffix).

## Package authoring no longer needed in .NET 9

**IMPORTANT**: Starting with .NET 9, you no longer need to edit a NuGet package's csproj to enable building and bump the version.
Keep in mind that we still need package authoring in .NET 8 and older versions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants