Skip to content

AsyncEnumerable.ThenBy with async key selector throws NullReferenceException: secondary keys not awaited #135343

Closed

Description

@agjini

Description

EnumerableSorter<TElement, TKey>.ComputeKeysAsync doesn't await the next sorter's key computation (OrderBy.cs#L351):

_next?.ComputeKeysAsync(elements, count, cancellationToken);

When the ThenBy key selector completes asynchronously, sorting starts before the secondary keys are computed. If the primary keys tie, Compare then reads a null _keys array.

Reproduction Steps

var sorted = await new[] { (A: 1, B: 2), (A: 1, B: 1) }
    .ToAsyncEnumerable()
    .OrderBy(x => x.A)
    .ThenBy(async (x, _) => { await Task.Delay(10); return x.B; })
    .ToListAsync();

Expected behavior

(1, 1), (1, 2)

Actual behavior

System.InvalidOperationException: Failed to compare two elements in the array.
 ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Linq.AsyncEnumerable.EnumerableSorter`2.Compare(Int32 index1, Int32 index2)

Suggested fix

if (_next is not null)
{
    await _next.ComputeKeysAsync(elements, count, cancellationToken);
}

Configuration

.NET 10.0.5, Linux x64 (bug still present on main)

Activity

  1. dotnet-policy-service commented on Oct 7, 2026

    @dotnet-policy-service
    Contributor

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

  2. eiriktsarpalis commented on Oct 7, 2026

    @eiriktsarpalis
    Member

    Reproduced on .NET 10.0.12 and .NET 11.0.0-rc.1.26425.128 on Windows x64. ThenByDescending and third-level asynchronous ordering are also affected. A faulted secondary selector can additionally be silently ignored when primary keys differ.

    This should remain open as a bug, with regression coverage for selectors that actually suspend and for exception propagation. A tested workaround is to compute the asynchronous keys in Select, then apply OrderBy/ThenBy with synchronous selectors.

  3. added a commit that references this issue on Oct 12, 2026
    1bde9a5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions