You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
The CancellationToken in a TaskCanceledException on ToListAsync does not match #2037
Why does the TaskCanceledException to be the given one but it isn´t
using(MyDbContextdbContext=new()){CancellationTokenSourcects=new();cts.Cancel();try{awaitdbContext.People.ToListAsync(cts.Token);}catch(TaskCanceledExceptionex)when(ex.CancellationToken==cts.Token)// that is what I´m expecting{Console.WriteLine("No problem");}catch(TaskCanceledExceptionex)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
@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.
awaitusingvarconnection=newSqlConnection("Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0;Encrypt=false");awaitconnection.OpenAsync();varcancelledToken=newCancellationToken(canceled:true);awaitusingvarcommand=newSqlCommand("SELECT 1",connection);try{awaitcommand.ExecuteReaderAsync(cancelledToken);}catch(OperationCanceledExceptione){Console.WriteLine($"Token on exception matches: {e.CancellationToken==cancelledToken}");}
Reacted by Javad Rahnama and Jakob Ferdinand Wegenschimmel
⚠️ 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.
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.
Activity
roji commentedon May 12, 2023
This is a bug in the SqlClient low-level driver; the same code works when using PostgreSQL.
JRahnama commentedon May 17, 2023
@JakobFerdinand Can you include a simple repro that does not use EFCore and reproduce the issue?
roji commentedon May 18, 2023
@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.
samsharma2700 commentedon Nov 12, 2024
This issue is on our radar and related to this #26 . We will evaluate internally and update.
priyankatiwari08 commentedon Sep 17, 2026
/triage
github-actions commentedon Sep 17, 2026
🔍 Triage Summary (on-demand re-triage)
Area\AsyncCancellationToken/OperationCanceledExceptionpropagation in async paths)Analysis
The issue reports that when an already-cancelled
CancellationTokenis passed to an async SqlClient call (e.g.,ExecuteReaderAsync), the resultingTaskCanceledException/OperationCanceledExceptiondoes not carry the original token —ex.CancellationTokenreturnsCancellationToken.Noneinstead 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: whereverOperationCanceledException/TaskCanceledExceptionis constructed internally, the triggering token should be passed to the exception constructor rather than omitted. This affects consumers who rely onex.CancellationTokento 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
TdsParser/SqlCommand/SqlDataReader(particularlyExecuteReaderAsync,ExecuteNonQueryAsync,ExecuteScalarAsync, and the internal task-cancellation helpers) and ensure everyOperationCanceledException/TaskCanceledExceptionthrown as a result of a caller-suppliedCancellationTokenis constructed with that token (e.g.,new OperationCanceledException(message, innerException, cancellationToken)), rather than defaulting toCancellationToken.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.ExecuteReaderAsync,ExecuteNonQueryAsync, andExecuteScalarAsync, assertingex.CancellationToken == suppliedToken.