Repository navigation
Description
I am witnessing this behavior in packages\netstandard.library\2.0.3\build\netstandard2.0\ref\netstandard.dll when running from a .Net Core 3.1 application.
When I call DbCommand.ExecuteReaderAsync with a CancellationToken and cancel it before it finishes, an exception is thrown that contains a TaskCanceledException buried down in the InnerExceptions. I expect that behavior, but the issue is that the TaskCanceledException.CancellationToken is not the CancellationToken that I provided to ExecuteReaderAsync. I do not know where this other CancellationToken is coming from, but I thought we were only supposed to suppress TaskCanceledException in our applications if it is for the provided CancellationToken, so I end up with a lot more unhandled exceptions than I want.
Is it safe to suppress any TaskCanceledException, no matter what CancellationToken it contains? Where does this mystery CancellationToken come from, and could ExecuteReaderAsync just return the CancellationToken given to it?
using (var cts = new CancellationTokenSource())
{
using (var cmd = db.GetSqlStringCommand(queryString))
{
cts.Cancel();
try
{
using (var rdr = cmd.ExecuteReaderAsync(cts.Token).Result)
{
}
}
catch (Exception ex3)
{
// if you inspect ex3, you will find a TaskCanceledException buried in InnerExceptions, but its CancellationToken is not cts.Token
throw;
}
}
}Additional Comments:
I have tested this with "System.Data.SqlClient.SqlCommand" and "Microsoft.Data.SqlClient.SqlCommand". The result is the same in both cases where the TaskCanceledException holds a new CancellationToken and the TaskCanceledException is wrapped in an AggregateException, so I have to dig down in the exception stack to find the TaskCanceledException , which means I cannot just catch TaskCanceledException.
System.AggregateException: One or more errors occurred. (A task was canceled.)
---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task1.get_Result()
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsBacklog
Activity
campersau commentedon Sep 2, 2021
Looks like this code is always creating a new cancelled
CancellationTokenbut it could just use the one which is passed in in the calling method. Also looks like this helper isn't really needed since it could be inlined?!https://github.com/dotnet/runtime/blob/6714f8175ff32daa501c7061a3237fafcead88c9/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs#L22
roji commentedon Sep 3, 2021
@Code3333 I'm assuming you are using System.Data.SqlClient or Microsoft.Data.SqlClient, can you please confirm (and say which one)?
This is actually a problem - async APIs are expected to raise a TaskCanceledException directly when cancellation occurs, without wrapping it; this is important to get the proper Status in the resulting Task (i.e. Canceled rather than Faulted). Assuming you're on SqlClient, this is tracked by #26.
That also sounds like a bug - pending confirmation that you're on SqlClient I'll transfer this over to that repo.
Coder3333 commentedon Sep 3, 2021
@roji I updated my original issue. This happens with both versions of SqlClient and the exception is wrapped in an AggregateException, instead of throwing a TaskCanceledException directly.
roji commentedon Sep 3, 2021
Transferred this to the SqlClient repo.
Specifically for AggregateException being thrown, see #1213 where this was fixed in at least some places for 4.0.0-preview.1 - maybe check that version out. If you're still seeing AggregateException being thrown, I'd recommend opening another issue on this repo with the repro, and leaving this issue to track the incorrect cancellation token.
JRahnama commentedon Sep 3, 2021
@roji thanks for transferring this. @Coder3333 I will look into it and update you shortly.
priyankatiwari08 commentedon Sep 17, 2026
/triage
github-actions commentedon Sep 17, 2026
🔍 Triage Summary (on-demand re-triage)
System.Data.SqlClientandMicrosoft.Data.SqlClientreproduce it, and provided repro code + stack trace)Area\AsyncTaskCanceledExceptiondirectly instead of wrapping), #2037 (similar report ofCancellationTokenmismatch on an async operation)Analysis
The reporter shows that calling
ExecuteReaderAsync(cancellationToken)and cancelling before completion surfaces aTaskCanceledException(wrapped in anAggregateExceptionvia.Result) whoseCancellationTokenproperty does not match the token passed by the caller. A maintainer (@campersau) already pinpointed the likely root cause: an internal helper (e.g. theAdapterUtil-equivalent) creates a new cancelledCancellationTokeninstead of propagating the one supplied by the caller, and this helper could likely be inlined or fixed to reuse the passed-in token. This affects the async command execution path (SqlCommand/DbCommandasync internals) and is a correctness/usability issue (masks proper cancellation detection for callers usingex.CancellationToken == myTokenpatterns) rather than a crash or data-loss bug. Severity: P2 — confirmed bug with a workaround (catching broadly / inspectingInnerExceptions), but the report predates the current codebase and no fresh repro/environment details have been reconfirmed on a current SqlClient version.Next Steps
SqlCommand/DbCommand.ExecuteReaderAsyncand related internals (search for where a cancellation-triggeredTaskCanceledExceptionis constructed) to confirm where a newCancellationTokenis manufactured instead of reusing the caller-supplied token, and to propagate the original token through to the thrownTaskCanceledException.AggregateExceptionrather than thrown directly, cross-check against the fix in Fix Async thread blocking on SqlConnection open for AAD modes #1213 (SqlClient 4.0.0-preview.1) and the related tracking issue Feature | Cancelling an async SqlClient operation throws SqlException, not TaskCanceledException #26 to see whether currentmainstill exhibits the wrapping behavior, or if only the token-mismatch part remains open.Microsoft.Data.SqlClientversion, .NET target framework, SQL Server version, and OS are currently affected, since this issue is from 2021 and the codebase has changed significantly since then.zdenek-jelinek commentedon Oct 16, 2026
I believe this part of the issue is an incorrect assumption. You shouldn't rely on
OperationCanceledException.CancellationTokencontaining the same token that was passed to the callee. The implementation could use a linked token source and so a different token internally.There has been a discussion about this topic some years ago at dotnet/runtime#22172. I don't know if that went anywhere in the end but I am not aware of any API that allows checking whether two cancellation tokens are related.