Skip to content

[NativeAOT][RuntimeAsync] NullReferenceException awaiting Task<ValueTask> / Task<ValueTask<T>> #135922

Closed

Description

@yushun-zhou

Description

Description

When compiling a .NET 11 RC2 application with NativeAOT and the experimental runtime-async=on feature, awaiting a Task<ValueTask> or Task<ValueTask<T>> can throw a System.NullReferenceException.

The issue was initially discovered with:

async ValueTask WorkAsync()
{
    await Task.Delay(1);
}

// NativeAOT + runtime-async=on: NullReferenceException
await Task.Run(() => WorkAsync()).ConfigureAwait(false);

// Works
await Task.Run(async () => await WorkAsync()).ConfigureAwait(false);

// Also works
await WorkAsync().ConfigureAwait(false);

The failing expression returns Task<ValueTask>, since Task.Run does not automatically unwrap ValueTask. Further investigation reproduced the exception using TaskCompletionSource<ValueTask>, confirming that Task.Run is not required to trigger it.

The failure is sensitive to the generic result type and compilation optimizations. Inserting an unrelated method call immediately before the await prevents the exception. Additionally, OptimizationPreference=Speed eliminates the failures, while Size reproduces them.

These findings suggest a possible optimization-sensitive NativeAOT Runtime Async code-generation issue involving ValueTask-family results and surrounding IL patterns.

Reproduction Steps

1. Project configuration

<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <PublishAot>true</PublishAot>
    <Features>runtime-async=on</Features>
    <OptimizationPreference>Size</OptimizationPreference>
</PropertyGroup>

2. Reproduction code

using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

await RunTest("Task.Run ValueTask", TestTaskRunAsync);
await RunTest("Task<ValueTask> Direct", TestDirectAsync);
await RunTest("Task<ValueTask> Local", TestLocalAsync);
await RunTest("Task<ValueTask> Barrier", TestBarrierAsync);
await RunTest("Task<ValueTask<int>>", TestValueTaskIntAsync);
await RunTest("Task<int> Control", TestIntAsync);
await RunTest("Task.Run Async Lambda", TestAsyncLambdaAsync);

static async Task RunTest(string name, Func<Task> test)
{
    Console.WriteLine(name);

    try
    {
        await test();
        Console.WriteLine("PASS");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}

static async ValueTask WorkAsync()
{
    await Task.Delay(1);
}

// Fails: original scenario
static async Task TestTaskRunAsync()
{
    await Task.Run(() => WorkAsync()).ConfigureAwait(false);
}

// Fails: direct Task<ValueTask> await
static async Task TestDirectAsync()
{
    var tcs = new TaskCompletionSource<ValueTask>();
    tcs.SetResult(ValueTask.CompletedTask);

    ValueTask inner = await tcs.Task.ConfigureAwait(false);
    await inner.ConfigureAwait(false);
}

// Fails: storing the Task in a local is insufficient
static async Task TestLocalAsync()
{
    var tcs = new TaskCompletionSource<ValueTask>();
    tcs.SetResult(ValueTask.CompletedTask);

    Task<ValueTask> outer = tcs.Task;
    ValueTask inner = await outer.ConfigureAwait(false);
    await inner.ConfigureAwait(false);
}

// Passes: inserting an unrelated method call
static async Task TestBarrierAsync()
{
    var tcs = new TaskCompletionSource<ValueTask>();
    tcs.SetResult(ValueTask.CompletedTask);

    Task<ValueTask> outer = tcs.Task;
    Barrier();

    ValueTask inner = await outer.ConfigureAwait(false);
    await inner.ConfigureAwait(false);
}

[MethodImpl(MethodImplOptions.NoInlining)]
static void Barrier()
{
}

// Fails: generic ValueTask result
static async Task TestValueTaskIntAsync()
{
    var tcs = new TaskCompletionSource<ValueTask<int>>();
    tcs.SetResult(new ValueTask<int>(42));

    ValueTask<int> inner = await tcs.Task.ConfigureAwait(false);
    await inner.ConfigureAwait(false);
}

// Passes: ordinary generic result
static async Task TestIntAsync()
{
    var tcs = new TaskCompletionSource<int>();
    tcs.SetResult(42);

    int result = await tcs.Task.ConfigureAwait(false);
}

// Passes: async lambda returns Task instead of ValueTask
static async Task TestAsyncLambdaAsync()
{
    await Task.Run(async () => await WorkAsync())
        .ConfigureAwait(false);
}

3. Publish and run

dotnet publish -c Release -r win-x64 `
    -p:PublishAot=true `
    -p:OptimizationPreference=Size

Compare against:

# NativeAOT speed optimization
dotnet publish -c Release -r win-x64 `
    -p:PublishAot=true `
    -p:OptimizationPreference=Speed

Use separate clean build/publish outputs for each configuration.

Expected behavior

Task.Run ValueTask
PASS
Task<ValueTask> Direct
PASS
Task<ValueTask> Local
PASS
Task<ValueTask> Barrier
PASS
Task<ValueTask<int>>
PASS
Task<int> Control
PASS
Task.Run Async Lambda
PASS

Actual behavior

Task.Run ValueTask
System.NullReferenceException: Object reference not set to an instance of an object.
   at Program.<<Main>$>g__TestTaskRunAsync|0_2()
--- End of stack trace from previous location ---
   at Program.<<Main>$>g__RunTest|0_0(String, Func`1)
Task<ValueTask> Direct
System.NullReferenceException: Object reference not set to an instance of an object.
   at Program.<<Main>$>g__TestDirectAsync|0_3()
--- End of stack trace from previous location ---
   at Program.<<Main>$>g__RunTest|0_0(String, Func`1)
Task<ValueTask> Local
System.NullReferenceException: Object reference not set to an instance of an object.
   at Program.<<Main>$>g__TestLocalAsync|0_4()
--- End of stack trace from previous location ---
   at Program.<<Main>$>g__RunTest|0_0(String, Func`1)
Task<ValueTask> Barrier
PASS
Task<ValueTask<int>>
System.NullReferenceException: Object reference not set to an instance of an object.
   at Program.<<Main>$>g__TestValueTaskIntAsync|0_7()
--- End of stack trace from previous location ---
   at Program.<<Main>$>g__RunTest|0_0(String, Func`1)
Task<int> Control
PASS
Task.Run Async Lambda
PASS

Regression?

No response

Known Workarounds

The following configurations avoid the failure in the tested cases:

  1. Remove the experimental runtime-async=on feature.
  2. Use OptimizationPreference=Speed instead of Size.

Configuration

dotnet --info

.NET SDK:
 Version:           11.0.100-rc.2.26504.105
 Commit:            820230c386
 Workload version:  11.0.100-manifests.939e2b91
 MSBuild version:   18.12.0-1.26504.105+820230c38

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.26200
 OS Platform: Windows
 RID:         win-x64
 Base Path:   C:\Program Files\dotnet\sdk\11.0.100-rc.2.26504.105

Other information

No response

Activity

  1. added
    untriaged
    on Oct 16, 2026
  2. dotnet-policy-service commented on Oct 16, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-threading-tasks
    See info in area-owners.md if you want to be subscribed.

  3. added
    area-CodeGen-coreclr
    and removed on Oct 17, 2026
  4. dotnet-policy-service commented on Oct 17, 2026

    @dotnet-policy-service
    Contributor

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

  5. yushun-zhou commented on Oct 17, 2026

    @yushun-zhou
    Author

    Additional findings from NativeAOT disassembly and WinDbg

    1. Failing TransparentAwait<ValueTask> call

    In the NativeAOT Release build with OptimizationPreference=Size, the generated caller contains:

    ; Caller
    movq 0x8(%rsi), %r8       ; Task<ValueTask>
    leaq -0x48(%rbp), %rcx   ; Result buffer
    xorl %edx, %edx          ; RDX = 0
    call TransparentAwait<ValueTask>

    The corresponding callee contains:

    ; Callee
    mov rsi, rcx
    mov rbx, rdx
    test dword ptr [rbx+34h], 1600000h

    WinDbg observations:

    Access violation - code c0000005 (first chance)
    
    RIP = Repro!AsyncHelpers.TransparentAwait<ValueTask>+0xc
          test dword ptr [rbx+34h], 1600000h
    
    RBX = 0
    RDX = 0
    R8  = 0x20356403740  ; Valid Task<ValueTask>
    

    The managed exception is:

    Unhandled exception. System.NullReferenceException:
    Object reference not set to an instance of an object.
       at Program.<Main>$(String[])
    

    At the failing call site, the caller places the Task<ValueTask> reference in R8, while the callee loads its task reference from RDX, which is zero.

    In the test program, all four observed exceptions occurred at the same callee instruction address, with four corresponding out-of-line call sites.

    2. Application IL and generated helper calls

    Inspection of the program IL using ildasm shows calls to:

    AsyncHelpers.Await<T>(ConfiguredTaskAwaitable<T>)
    

    TransparentAwait<T> does not appear in the application's IL or in the IL body of AsyncHelpers.Await<T>.

    The NativeAOT-generated assembly contains the out-of-line TransparentAwait<ValueTask> invocation.

    Related runtime implementation: #129896 (impWrapTopOfStackInAwait / getAwaitReturnCall).

    3. Passing case with an intervening Barrier() call

    Adding an empty method marked with [MethodImpl(MethodImplOptions.NoInlining)] immediately before the await produces:

    ; Barrier, Size build
    movq  0x8(%rbx), %rbx
    callq 0x140051580           ; Barrier()
    movq  %rbx, -0x60(%rbp)     ; Awaitable.Task
    movl  $0, -0x58(%rbp)       ; ConfigureAwaitOptions.None
    leaq  -0x60(%rbp), %rdx     ; Awaitable address
    leaq  -0x40(%rbp), %rcx     ; Result buffer
    callq Await<ValueTask>(ConfiguredTaskAwaitable<ValueTask>)

    In this build:

    • The configured awaitable is stored on the stack.
    • The generated call targets AsyncHelpers.Await<ValueTask>(ConfiguredTaskAwaitable<ValueTask>).
    • The out-of-line TransparentAwait<ValueTask> call is absent from this path.
    • The test completes successfully.
  6. added a commit that references this issue on Oct 19, 2026
    994a6d6
  7. added a commit that references this issue on Oct 19, 2026
    c4ed8c8
  8. removed
    untriaged
    on Oct 19, 2026
  9. locked and limited conversation to collaborators on Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrruntime-async

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions