Skip to content

SqlCommand async Task may never complete because of unhandled exception #3067

@SergeyBokhantsev

Description

@SergeyBokhantsev

Describe the bug

Async Task of SqlCommand sometimes could never go to Completed state (if exception occurs during command execution).
Thus, if you await the SqlCommand then your code may stuck forever at waiting the task completion.

Observed case:
There is a trivial code to interact with Azure SQL DB via EntityFramework. We noticed that sometimes the module that is working with DB freezes forever. Analyzing memory dumps we saw that it is always stuck awaiting EntityFramework operations like Select, Find, SaveChangesAsync etc.
In every case there is an unobserved exception logged also with the following details about the root exception:
Invalid operation. The connection is closed.
System.AggregateException: System.InvalidOperationException:
at Microsoft.Data.SqlClient.SqlConnection.GetOpenTdsConnection
at Microsoft.Data.SqlClient.SqlCommand+<>c__DisplayClass186_0.b__0
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop
at System.Threading.Tasks.Task.ExecuteWithThreadLocal

To reproduce

Unfortunately I don't have code to reproduce the issue because in our case the issue was caused by a sporadic network connection problem.
But taking into account the above exception call stack, the issue in source code can be seen:

I tested the described case by compiling custom SqlClient.dll where an artificial exceptions was thrown in lines 2407 and 2448, and can confirm it causes same behavior and Entity Framework operation stuck forever awaiting SqlCommand.

Expected behavior

Exceptions during SqlCommand execution must not prevent root Task from completion.

Further technical details

Microsoft.Data.SqlClient version: 5.2.0
EntityFramework 6.4.4
.Net 8

Metadata

Metadata

Assignees

Labels

Triage Done ✔️Issues that are triaged by dev team and are in investigation.

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions