Skip to content

Native AOT runtime-async continuation dispatch allocates thread-static storage on first completion per thread #137474

Open

Description

@thomhurst

Description

On .NET 11 Native AOT, completing an IValueTaskSource on a dedicated thread allocates managed memory when it resumes a runtime-async Task consumer for the first time on that thread. Later completions allocate zero bytes. The equivalent .NET 10 Native AOT consumer does not allocate on the completion thread. This makes first-use allocation counters include runtime initialization even when the source itself retains all its storage.

Reproduction

Create a console project with this project file (no external packages):

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>net10.0;net11.0</TargetFrameworks>
    <PublishAot>true</PublishAot>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

Use this Program.cs:

using System.Threading.Tasks.Sources;
for (var thread = 0; thread < 3; thread++)
{
    var source = new Source();
    using var release = new AutoResetEvent(false);
    using var finished = new AutoResetEvent(false);
    var bytes = new long[5];
    var worker = new Thread(() =>
    {
        for (var round = 0; round < bytes.Length; round++)
        {
            release.WaitOne();
            var before = GC.GetAllocatedBytesForCurrentThread();
            source.Complete();
            bytes[round] = GC.GetAllocatedBytesForCurrentThread() - before;
            finished.Set();
        }
    });
    worker.Start();
    for (var round = 0; round < bytes.Length; round++)
    {
        var consumer = Consume(source.Wait());
        release.Set();
        finished.WaitOne();
        if (!consumer.IsCompletedSuccessfully) throw new Exception("Consumer did not complete inline");
    }
    worker.Join();
    Console.WriteLine(string.Join(", ", bytes));
}
static async Task Consume(ValueTask pending) => await pending.ConfigureAwait(false);
sealed class Source : IValueTaskSource
{
    private ManualResetValueTaskSourceCore<bool> _core;
    internal ValueTask Wait() { _core.Reset(); return new(this, _core.Version); }
    internal void Complete() => _core.SetResult(true);
    public void GetResult(short token) => _core.GetResult(token);
    public ValueTaskSourceStatus GetStatus(short token) => _core.GetStatus(token);
    public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => _core.OnCompleted(continuation, state, token, flags);
}

Publish into a fresh project/output for each variant (changing Features alone can reuse previously compiled output):

dotnet publish -c Release -f net11.0 -r osx-arm64 -p:Features=runtime-async=on -o out
./out/probe

For the comparison, publish a fresh copy targeting net10.0 without Features, or net11.0 without Features.

Configuration

SDK 11.0.100 (297acf930f), runtime 11.0.0, macOS 27.2, arm64. Comparison: runtime 10.0.14 from SDK 10.0.403. No profiler or debugger is required to reproduce.

Regression and data

With runtime async enabled, a representative .NET 11 output is:

256, 0, 0, 0, 0
224, 0, 0, 0, 0
224, 0, 0, 0, 0

.NET 10 and .NET 11 with compiler-generated state machines print all zeros for this minimal example. Consumer creation is outside the worker counter, and the main thread checks completion without blocking on a Task.

Analysis

An LLDB breakpoint on Internal.Runtime.ThreadStatics.AllocateThreadStaticStorageForType stops on the completion thread inside AsyncHelpers.RuntimeAsyncTask<VoidTaskResult>.DispatchContinuations, at both the t_runtimeAsyncAwaitState and AsyncDispatcherInfo.t_current accesses:

The same thread-static accesses remain in main; I found no matching open or closed issue or unreleased fix. The larger application that exposed this was Relayer (tracking issue); this reproduction does not reference it.

Could Native AOT avoid these first-dispatch managed allocations for runtime-async continuations?

Activity

  1. added
    untriaged
    on Nov 13, 2026
  2. dotnet-policy-service commented on Nov 13, 2026

    @dotnet-policy-service
    Contributor

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

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Threadingruntime-asyncuntriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions