Skip to content

DbCommand.ExecuteReaderAsync throws TaskCanceledException with wrong CancellationToken #1250

Open

Description

@Coder3333

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()

Activity

  1. campersau commented on Sep 2, 2021

    @campersau
    Contributor

    Looks like this code is always creating a new cancelled CancellationToken but 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

  2. roji commented on Sep 3, 2021

    @roji
    Member

    @Code3333 I'm assuming you are using System.Data.SqlClient or Microsoft.Data.SqlClient, can you please confirm (and say which one)?

    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 [...]

    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.

    [...] the issue is that the TaskCanceledException.CancellationToken is not the CancellationToken that I provided to ExecuteReaderAsync

    That also sounds like a bug - pending confirmation that you're on SqlClient I'll transfer this over to that repo.

  3. Coder3333 commented on Sep 3, 2021

    @Coder3333
    Author

    @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.

    @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 dotnet/SqlClient#26.

  4. transferred this issue fromdotnet/runtimeon Sep 3, 2021
  5. roji commented on Sep 3, 2021

    @roji
    Member

    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.

  6. JRahnama commented on Sep 3, 2021

    @JRahnama
    Contributor

    @roji thanks for transferring this. @Coder3333 I will look into it and update you shortly.

  7. moved this from To triage to Needs Response in SqlClient Boardon Jan 5, 2026
  8. moved this from Needs Response to Backlog in SqlClient Boardon Apr 1, 2026
  9. priyankatiwari08 commented on Sep 17, 2026

    @priyankatiwari08
    Contributor

    /triage

  10. github-actions commented on Sep 17, 2026

    @github-actions

    🔍 Triage Summary (on-demand re-triage)

    Check Result
    Issue type Bug
    Environment ⚠️ Missing: exact SqlClient version, .NET target framework, SQL Server version, Operating system (reporter confirmed both System.Data.SqlClient and Microsoft.Data.SqlClient reproduce it, and provided repro code + stack trace)
    Area Area\Async
    Duplicates Related (not exact duplicates): #26 (async cancellation should surface TaskCanceledException directly instead of wrapping), #2037 (similar report of CancellationToken mismatch on an async operation)
    Regression Not indicated

    Analysis

    The reporter shows that calling ExecuteReaderAsync(cancellationToken) and cancelling before completion surfaces a TaskCanceledException (wrapped in an AggregateException via .Result) whose CancellationToken property does not match the token passed by the caller. A maintainer (@campersau) already pinpointed the likely root cause: an internal helper (e.g. the AdapterUtil-equivalent) creates a new cancelled CancellationToken instead 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/DbCommand async internals) and is a correctness/usability issue (masks proper cancellation detection for callers using ex.CancellationToken == myToken patterns) rather than a crash or data-loss bug. Severity: P2 — confirmed bug with a workaround (catching broadly / inspecting InnerExceptions), but the report predates the current codebase and no fresh repro/environment details have been reconfirmed on a current SqlClient version.

    Next Steps

    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 #1250 · copilot · auto · 57.9 AIC · ⌖ 14.2 AIC · ⊞ 11.9K · ◷

  11. zdenek-jelinek commented on Oct 16, 2026

    @zdenek-jelinek

    the issue is that the TaskCanceledException.CancellationToken is not the CancellationToken that I provided to ExecuteReaderAsync

    I believe this part of the issue is an incorrect assumption. You shouldn't rely on OperationCanceledException.CancellationToken containing 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.

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