Skip to content

Feature | Cancelling an async SqlClient operation throws SqlException, not TaskCanceledException #26

Description

@roji

When using a cancellation token to cancel an SqlClient async operation, an SqlException is thrown rather than TaskCanceledException. This seems like problematic behavior, here's some analysis.

On the problematic side, standard async APIs generally throw TaskCanceledException, and SqlClient is doing something different and therefore unexpected. Also, as a result, canceled SqlClient tasks don't have status Canceled, they're Faulted instead. This makes differentiating cancellations from real exceptions more difficult, and the problem is compounded if the SqlClient call is just part of a larger async operation (which again, will be faulted instead of canceled unless some manual specific handling is involved).

The argument for the current behavior seems to be that all of SqlClient's server and network errors are raised as SqlException, making it easy to catch all database errors under a single exception type. On the other hand, it seems that cancellation isn't really an error condition as it's been requested by the user and is expected to occur. The TaskCanceledException is simply a mechanism for conveying the cancellation up the stack.

For the record, this was originally reported by @mikkeljohnsen for Npgsql in npgsql/npgsql#1146. Whatever is decided here for SqlClient will also be adopted for Npgsql (which currently behaves like SqlClient in this respect).

Activity

  1. GSPP commented on Jun 9, 2016

    @GSPP

    If this is changed the exception should allow to tell the difference between:

    1. Timeout
    2. SqlCommand.Cancel
    3. Some other external cancellation arrived through a CancellationToken

    My fear is that it becomes hard to analyze error logs. Also, sometimes programmatic action is required. Maybe you don't want to send an error mail to the ops team for explicit cancellations but you do want to send one for timeouts.

    TaskCanceledException is not exactly the nicest exception possible and it's quite nasty already with HttpClient.

  2. roji commented on Jun 9, 2016

    @roji
    MemberAuthor

    @GSPP, I think distinguishing between timeouts and cancellations would be easy in any case - TaskCanceledException would only be thrown for cancellations, not timeouts. SqlException already provides the means to programmatically understand exactly what happened. The question here is only whether cancellations should be be raised as SqlException or as TaskCanceledException.

  3. GSPP commented on Jun 9, 2016

    @GSPP

    Good point.

  4. bgrainger commented on Nov 6, 2017

    @bgrainger

    When developing MySqlConnector, I didn't check the SqlClient behaviour first, but just assumed that throwing OperationCanceledException (and transitioning the Task returned from ExecuteXAsync to the Canceled state) was the right thing to do. (At the moment, I plan to keep this behaviour instead of changing it to match SqlClient and Npgsql.)

    Throwing:
    https://github.com/mysql-net/MySqlConnector/blob/a06bf08763fa97f3e4c7c0157a0e54d9d5b8bccf/src/MySqlConnector/MySqlClient/CommandExecutors/TextCommandExecutor.cs#L64-L67

    Example test:
    https://github.com/mysql-net/MySqlConnector/blob/a06bf08763fa97f3e4c7c0157a0e54d9d5b8bccf/tests/SideBySide/CancelTests.cs#L186

  5. mikkeljohnsen commented on Nov 6, 2017

    @mikkeljohnsen

    @bgrainger Yes it is the logical thing to do. The SqlClient is doing it wrong and should change it ASAP.

    I think Npgsql should follow your lead and do the right thing.

  6. roji commented on Nov 6, 2017

    @roji
    MemberAuthor

    As this hasn't even received a comment in such a long time, I'll go ahead and change Npgsql's behavior for 3.3.

    I really do hope Microsoft improves their attitude towards database access and ADO.NET, it's quite frustrating for things to receive zero attention at all - Entity Framework is important but so is raw SQL access (@divega maybe you can help push again)

  7. removed their assignment
    on Mar 30, 2018
  8. JackLiang5 commented on Mar 20, 2019

    @JackLiang5

    Ref to Cancellation in Managed Threads ( https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads?view=netframework-4.7.2 )

    Cancellations should be raised as OperationCanceledException or its derived class (e.g. TaskCanceledException). Usually, exception handler (including try/catch) will process OperationCanceledException specially. There're some examples in the referred page. Raising other exception like SqlException will break these examples.

  9. divega commented on May 15, 2019

    @divega

    As recently announced in the .NET Blog, focus on new SqlClient features an improvements is moving to the new Microsoft.Data.SqlClient package. For this reason, we are moving this issue to the new repo at https://github.com/dotnet/SqlClient. We will still use https://github.com/dotnet/corefx to track issues on other providers like System.Data.Odbc and System.Data.OleDB, and general ADO.NET and .NET data access issues.

  10. transferred this issue fromdotnet/corefxon May 15, 2019
  11. added this to the milestone on May 21, 2019
  12. added
    Breaking Change 🔨
    on Oct 7, 2019
  13. cheenamalhotra commented on Oct 7, 2019

    @cheenamalhotra
    Member

    Acknowledged.
    As it seems to be a breaking API change, we'll consider fixing it with other API changes, when that happens.

  14. virzak commented on Dec 7, 2019

    @virzak
    Contributor

    I ran into this as well.

    Having to use a hack to suppress. Is there a better way to handle this in the meantime?

    catch (OperationCanceledException)
    {
    }
    // Fixme:
    // Remove this catch when issue is resolved: https://github.com/dotnet/SqlClient/issues/26
    catch (Microsoft.Data.SqlClient.SqlException sqlex)
    {
        var errors = sqlex.Errors;
        var isCancelled = false;
        foreach (var error in errors)
        {
            if (!(error is Microsoft.Data.SqlClient.SqlError sqlError))
                continue;
            if (sqlError.Message == "Operation cancelled by user.")
            {
                isCancelled = true;
            }
        }
    
        if (!isCancelled)
            throw;
    }
  15. 31 remaining items

  16. Wraith2 commented on Oct 16, 2025

    @Wraith2
    Contributor

    I think the team has changed around so johnny may no longer be available to look at it. You probably want to tag the @dotnet/sqlclientdevteam and it may be something that @benrr101 be interested in.

  17. moved this from To triage to Backlog in SqlClient Boardon Nov 20, 2025
  18. matthetherington commented on Dec 8, 2025

    @matthetherington

    We're using UseAzureSql with EnableRetryOnFailure - which adds its own ExecutionStrategy and means the fix in #26 (comment) replaces it.

    So here's a slightly modified version I put together, with SqlServerRetryingExecutionStrategy as the base class instead of SqlServerExecutionStrategy:

    #pragma warning disable EF1001
    public class FixSqlClientIssue26ExecutionStrategy(ExecutionStrategyDependencies dependencies)
        : SqlServerRetryingExecutionStrategy(dependencies)
    #pragma warning restore EF1001
    {
        private const string OperationCanceledByUserMessage = "Operation cancelled by user.";
    
        public static IExecutionStrategy Create(ExecutionStrategyDependencies dependencies) =>
            new FixSqlClientIssue26ExecutionStrategy(dependencies);
    
        protected override bool ShouldRetryOn(Exception exception)
        {
            if (exception is SqlException sqlException)
            {
                foreach (SqlError error in sqlException.Errors)
                {
                    if (
                        string.Equals(
                            error.Message,
                            OperationCanceledByUserMessage,
                            StringComparison.Ordinal
                        )
                    )
                    {
                        return false;
                    }
                }
            }
            return base.ShouldRetryOn(exception);
        }
    }

    used like:

    opt.UseAzureSql(
        connectionString,
        opts =>
        {
            // The order is important here. Add the ExecutionStrategy after EnableRetryOnFailure
            opts.EnableRetryOnFailure();
            opts.ExecutionStrategy(FixSqlClientIssue26ExecutionStrategy.Create);
        }
    )
  19. changed the issue type fromtoon Dec 16, 2025
  20. changed the title [-]Cancelling an async SqlClient operation throws SqlException, not TaskCanceledException[/-] [+]Feature | Cancelling an async SqlClient operation throws SqlException, not TaskCanceledException[/+] on Mar 31, 2026
  21. elachlan commented on Apr 30, 2026

    @elachlan

    We specifically catch OperationCanceledException so that we can return Status499ClientClosedRequest from our API.

    The behavior is inconsistent as we are getting SqlException occasionally.

    Microsoft.Data.SqlClient.SqlException: A severe error occurred on the current command.  The results, if any, should be discarded.
    Operation cancelled by user.
    at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__195_0(System.Threading.Tasks.Task`1 result) at offset 8
    at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke() at offset 36
    at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.<ExecuteReaderAsync>d__18.MoveNext() at offset 748
    at Microsoft.EntityFrameworkCore.Query.Internal.AsyncEnumerator.<InitializeReaderAsync>d__21.MoveNext() at offset 265
    at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.<ExecuteAsync>d__7`2.MoveNext() at offset 147
    at Microsoft.EntityFrameworkCore.Query.Internal.AsyncEnumerator.<MoveNextAsync>d__20.MoveNext() at offset 236
    at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToListAsync>d__67`1.MoveNext() at offset 213
    
  22. 0xced commented on May 7, 2026

    @0xced
    Contributor

    I finally turned my experiment into a proper NuGet package: WorkaroundSqlClientIssue26

    It's super easy to use, see the README on NuGet or in the repository.

    @matthetherington This new package supports another execution strategy, so you can chain EnableRetryOnFailure() and WorkAroundSqlClientIssue26().

    @elachlan If you use EF Core then you'll be able to catch OperationCanceledException with this workaround.

  23. added this to the 8.0.0 milestone on Sep 11, 2026
  24. priyankatiwari08 commented on Sep 17, 2026

    @priyankatiwari08
    Contributor

    /triage

  25. 0xced commented on Sep 17, 2026

    @0xced
    Contributor

    🔍 Triage Summary (on-demand re-triage)

    Check Result
    Issue type Bug (really, it's a bug)
    Area The abyss of forgotten bugs
    Duplicates #1250, dotnet/runtime#46835, related: #2037
    Regression Not a regression, the behaviour has always been wrong

    Analysis

    Throwing randomly InvalidOperationException, SqlException or TaskCanceledException but with a wrong cancellation token upon cancellation has cost thousands (millions?) of engineering hours. See also: principle of least astonishment.

    Next Steps

    • Maintainers should fix the bug and throw an OperationCanceledException with the proper CancellationToken when cancellation happens.
    • Release notes of the next major version should mention that the bug has been fixed.

    Note: This triage summary is written by a fed up user. No AI was used to write this summary.

  26. modified the milestones: 8.0.0, 8.1.0 on Nov 4, 2026
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

    Breaking Change 🔨

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions