Skip to content

SqlDataReader.ReadAsync blocks same thread to execute synchronous code #24800

@geleems

Description

@geleems

Customer reported an issue for SqlDataReader.ReadAsync() method actually runs synchronously, and it blocks the calling thread until data is fed from SQL Server.

Here is the detail description of the issue from the customer:

I want to be able to write asynchronous code in C# which can reliably yield a Task upon anything that, in synchronous code, would block.
All of my setup code and the initialization of the SqlCommand is fairly small and does not have a performance hit if I run it on a UI thread in winforms.
However, because ReadAsync() does not actually always run asynchronously, depending on the query, even though I have await MyFunctionWhichCallsReadAsync();, the effect is that the UI thread is blocked causing a bad experience for the user.
It is misleading that ReadAsync() is named "Async" when it will block the caller.
This prevents a caller which would start multiple asynchronous operation and wait for them concurrently from doing so.
E.g., if I do the following, no concurrency will happen even though it should:

var readTask = reader.ReadAsync();
var backgroundThingTask = DoSomethingElseConcurrentlyAsync();
var readResult = await readTask;
await backgroundThingTask;

This is because reader.ReadAsync() will block without returning a Task until it actually receives data from SQL Server.

Repro code: https://github.com/binki/connect3139210

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions