Repository navigation
Description
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=SizeCompare against:
# NativeAOT speed optimization
dotnet publish -c Release -r win-x64 `
-p:PublishAot=true `
-p:OptimizationPreference=SpeedUse 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:
- Remove the experimental
runtime-async=onfeature. - Use
OptimizationPreference=Speedinstead ofSize.
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
dotnet-policy-service commentedon Oct 16, 2026
Tagging subscribers to this area: @dotnet/area-system-threading-tasks
See info in area-owners.md if you want to be subscribed.
dotnet-policy-service commentedon Oct 17, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
yushun-zhou commentedon Oct 17, 2026
Additional findings from NativeAOT disassembly and WinDbg
1. Failing
TransparentAwait<ValueTask>callIn the NativeAOT Release build with
OptimizationPreference=Size, the generated caller contains:The corresponding callee contains:
WinDbg observations:
The managed exception is:
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
ildasmshows calls to:TransparentAwait<T>does not appear in the application's IL or in the IL body ofAsyncHelpers.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()callAdding an empty method marked with
[MethodImpl(MethodImplOptions.NoInlining)]immediately before the await produces:In this build:
AsyncHelpers.Await<ValueTask>(ConfiguredTaskAwaitable<ValueTask>).TransparentAwait<ValueTask>call is absent from this path.ILC: make IsAsyncCall instantiation-invariant
ILC: make IsAsyncCall instantiation-invariant (#136002)
[release/11.0] ILC/crossgen2: make IsAsyncCall instantiation-invariant (