Skip to content

The CancellationToken in a TaskCanceledException on ToListAsync does not match #2037

Open

Description

@JakobFerdinand

Why does the TaskCanceledException to be the given one but it isn´t

using (MyDbContext dbContext = new())
{
    CancellationTokenSource cts = new();
    cts.Cancel();

    try
    {
        await dbContext.People.ToListAsync(cts.Token);
    }
    catch (TaskCanceledException ex) when (ex.CancellationToken == cts.Token) // that is what I´m expecting
    {
        Console.WriteLine("No problem"); 
    }
    catch (TaskCanceledException ex) when (ex.CancellationToken == CancellationToken.None) // that is what is happening
    {
        Console.WriteLine("Why?");
    }
}

Can you explain the given cts.Token is not passed to the exception?

provider and version information

EF Core version: 7.0.5
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 7.0
Operating system: Windows 11
IDE: Visual Studio 2022 17.5

Activity

  1. transferred this issue fromdotnet/efcoreon May 12, 2023
  2. roji commented on May 12, 2023

    @roji
    Member

    This is a bug in the SqlClient low-level driver; the same code works when using PostgreSQL.

  3. JRahnama commented on May 17, 2023

    @JRahnama
    Contributor

    @JakobFerdinand Can you include a simple repro that does not use EFCore and reproduce the issue?

  4. roji commented on May 18, 2023

    @roji
    Member

    @JRahnama here you go; the following code prints False with SqlClient, but True with e.g. Npgsql.

    Note that this specifically tests for passing an already-cancelled token to a SqlClient call. There are other paths where the token is cancelled only after the operation already started - these also need to throw an exception containing the token. Basically wherever you're creating an OperationCanceledException/TaskCanceledException, the triggering token should be passed in.

    await using var connection = new SqlConnection("Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0;Encrypt=false");
    await connection.OpenAsync();
    
    var cancelledToken = new CancellationToken(canceled: true);
    await using var command = new SqlCommand("SELECT 1", connection);
    
    try
    {
        await command.ExecuteReaderAsync(cancelledToken);
    }
    catch (OperationCanceledException e)
    {
        Console.WriteLine($"Token on exception matches: {e.CancellationToken == cancelledToken}");
    }
  5. samsharma2700 commented on Nov 12, 2024

    @samsharma2700
    Contributor

    This issue is on our radar and related to this #26 . We will evaluate internally and update.

  6. moved this from To triage to Backlog in SqlClient Boardon Nov 21, 2025
  7. priyankatiwari08 commented on Sep 17, 2026

    @priyankatiwari08
    Contributor

    /triage

  8. github-actions commented on Sep 17, 2026

    @github-actions

    🔍 Triage Summary (on-demand re-triage)

    Check Result
    Issue type Bug
    Environment ⚠️ Missing: SqlClient version, .NET target framework, and OS for the minimal (non-EFCore) repro provided in comments. Original report used EF Core 7.0.5 / .NET 7.0 / Windows 11, but the confirmed low-level repro (SqlCommand.ExecuteReaderAsync with a pre-cancelled token) does not state the SqlClient package version or OS it was validated against.
    Area Area\Async
    Duplicates Potentially related: #26 (already linked by a maintainer as related — both concern CancellationToken/OperationCanceledException propagation in async paths)
    Regression Not indicated — appears to be a long-standing design gap rather than a regression from a specific version

    Analysis

    The issue reports that when an already-cancelled CancellationToken is passed to an async SqlClient call (e.g., ExecuteReaderAsync), the resulting TaskCanceledException/OperationCanceledException does not carry the original token — ex.CancellationToken returns CancellationToken.None instead of the token that triggered cancellation. A maintainer (@roji) confirmed this with a minimal SqlClient-only repro and noted the bug likely spans multiple code paths: wherever OperationCanceledException/TaskCanceledException is constructed internally, the triggering token should be passed to the exception constructor rather than omitted. This affects consumers who rely on ex.CancellationToken to distinguish caller-initiated cancellation from other cancellation sources (e.g., command timeouts), which is a common pattern for retry/telemetry logic. Severity: P2 — not a crash or data-correctness bug, but it breaks a documented .NET cancellation contract and has visible user impact (2 community 👍 on the confirming comment) and has been open since 2023 with an internal note in 2024 that it's "on our radar."

    Next Steps

    • Assign this issue to Copilot coding agent to investigate the async cancellation paths in TdsParser/SqlCommand/SqlDataReader (particularly ExecuteReaderAsync, ExecuteNonQueryAsync, ExecuteScalarAsync, and the internal task-cancellation helpers) and ensure every OperationCanceledException/TaskCanceledException thrown as a result of a caller-supplied CancellationToken is constructed with that token (e.g., new OperationCanceledException(message, innerException, cancellationToken)), rather than defaulting to CancellationToken.None. Pay particular attention to the pre-cancelled-token fast path (where the token is already cancelled before the operation starts) versus mid-operation cancellation, since both need correct token propagation.
    • Review Feature | Cancelling an async SqlClient operation throws SqlException, not TaskCanceledException #26 for any overlapping root cause or prior investigation notes before starting new work, to avoid duplicate effort.
    • Add regression tests covering both the "already-cancelled token" and "cancelled during execution" scenarios for the sync and async paths of ExecuteReaderAsync, ExecuteNonQueryAsync, and ExecuteScalarAsync, asserting ex.CancellationToken == suppliedToken.

    Note: This triage summary is auto-generated by an AI agent. The analysis and suggestions above have not been verified by a human maintainer. Please treat as preliminary guidance only.

    Generated by SqlClient Issue Auto-Triage for #2037 · copilot · auto · 67.7 AIC · ⌖ 13.1 AIC · ⊞ 11.9K · ◷

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

    No labels
    No labels

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions