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
Feature | Cancelling an async SqlClient operation throws SqlException, not TaskCanceledException #26
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).
Reacted by Joseph Musser, moleee, Uygar Yilmaz, Augusto Proiete, Peter Toft Jølving, hallidev, Victor Irzak, Joel Weiss, Krzysztof Branicki, Piotr Szarzec and 68 more
Reacted by Joseph Musser, Maxim Cherednik, Uygar Yilmaz, Victor Irzak, Krzysztof Branicki, Mike Goatly, Ivan Duka and Erkan Okyay
If this is changed the exception should allow to tell the difference between:
Timeout
SqlCommand.Cancel
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.
@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.
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.)
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)
Reacted by Joseph Musser, Sergey Kovalenko, Uygar Yilmaz, Krzysztof Branicki, Michael Conrad, Dion Leurink and Michael Hawkins
Reacted by Joseph Musser, Uygar Yilmaz and Krzysztof Branicki
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.
Reacted by Maxim Cherednik, Victor Irzak, Krzysztof Branicki and Robert Haken
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/26catch(Microsoft.Data.SqlClient.SqlExceptionsqlex){varerrors=sqlex.Errors;varisCancelled=false;foreach(varerrorinerrors){if(!(errorisMicrosoft.Data.SqlClient.SqlErrorsqlError))continue;if(sqlError.Message=="Operation cancelled by user."){isCancelled=true;}}if(!isCancelled)throw;}
Reacted by Tommy Vernieri, AgentFire, Ivan Duka, Thomas Eyde and Alin Velea
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.
opt.UseAzureSql(connectionString,
opts =>{// The order is important here. Add the ExecutionStrategy after EnableRetryOnFailureopts.EnableRetryOnFailure();opts.ExecutionStrategy(FixSqlClientIssue26ExecutionStrategy.Create);})
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
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
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.
Reacted by Justin Adler, myGoldstein, pblackburn68, MisinformedDNA, Zdeněk Jelínek and Frulfump
Reacted by danpaul88, Luca Domenichini, Damien Braillard, Joe Amenta, Matt Hetherington, Alex Meyer-Gleaves, Justin Adler, myGoldstein, Oli, MisinformedDNA and 5 more
Activity
GSPP commentedon Jun 9, 2016
If this is changed the exception should allow to tell the difference between:
SqlCommand.CancelCancellationTokenMy 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.
TaskCanceledExceptionis not exactly the nicest exception possible and it's quite nasty already withHttpClient.roji commentedon Jun 9, 2016
@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.
GSPP commentedon Jun 9, 2016
Good point.
bgrainger commentedon Nov 6, 2017
When developing MySqlConnector, I didn't check the SqlClient behaviour first, but just assumed that throwing
OperationCanceledException(and transitioning theTaskreturned fromExecuteXAsyncto theCanceledstate) 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
mikkeljohnsen commentedon Nov 6, 2017
@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.
roji commentedon Nov 6, 2017
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)
JackLiang5 commentedon Mar 20, 2019
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.
divega commentedon May 15, 2019
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.
cheenamalhotra commentedon Oct 7, 2019
Acknowledged.
As it seems to be a breaking API change, we'll consider fixing it with other API changes, when that happens.
virzak commentedon Dec 7, 2019
I ran into this as well.
Having to use a hack to suppress. Is there a better way to handle this in the meantime?
31 remaining items
Wraith2 commentedon Oct 16, 2025
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.
matthetherington commentedon Dec 8, 2025
We're using
UseAzureSqlwithEnableRetryOnFailure- 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
SqlServerRetryingExecutionStrategyas the base class instead ofSqlServerExecutionStrategy:used like:
[-]Cancelling an async SqlClient operation throws SqlException, not TaskCanceledException[/-][+]Feature | Cancelling an async SqlClient operation throws SqlException, not TaskCanceledException[/+]elachlan commentedon Apr 30, 2026
We specifically catch
OperationCanceledExceptionso that we can returnStatus499ClientClosedRequestfrom our API.The behavior is inconsistent as we are getting
SqlExceptionoccasionally.0xced commentedon May 7, 2026
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()andWorkAroundSqlClientIssue26().@elachlan If you use EF Core then you'll be able to catch
OperationCanceledExceptionwith this workaround.feat: add SQL Server provider with CI conformance execution (M5-3) (#50)
Recognise an interruption by the token, not by the exception's type
priyankatiwari08 commentedon Sep 17, 2026
/triage
0xced commentedon Sep 17, 2026
🔍 Triage Summary (on-demand re-triage)
Analysis
Throwing randomly
InvalidOperationException,SqlExceptionorTaskCanceledExceptionbut with a wrong cancellation token upon cancellation has cost thousands (millions?) of engineering hours. See also: principle of least astonishment.Next Steps
OperationCanceledExceptionwith the properCancellationTokenwhen cancellation happens.