I am looking at the code for DbDataReader (also DbCommand) at MS reference and can't figure out what is async in ReadAsync() method.
virtual public Task<bool> ReadAsync(CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested) {
return ADP.CreatedTaskWithCancellation<bool>();
}
else {
try {
return Read() ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e) {
return ADP.CreatedTaskWithException<bool>(e);
}
}
}
The ReadAsync method just calls Read method and returns a complete task. Doesn't this block the calling thread the same way as calling Read directly?
I have noticed the same pattern in DbCommand ExecuteReaderAsync and other methods. They just call the sync versions and return completed Tasks.
What am I missing here?
UPDATE: I did not miss anything, as @PeterBons explained nicely (also in the documentation). I still don't like it, but that's my problem.
You are looking at a virtual method in an abstract class. If you want (future) implementations to be able to do some truly async work you will have to define a method signature that allows that. So it should return a
TaskorTask<T>. Remember that just using a Task does not make anything asynchronous, it makes it awaitable.The use of the
Task<bool>return type in this example virtual method is to facilitate other classes that derive from DbDataReader to provide real async behavior in their implementation of ReadAsync.For example, a truly async implementation could do something like
As you can see you can now have async and non async implementations, without having to alter the method signature.
Since you can easily call synchronous code from an async method this is the way to go. Calling async code from a synchronous method is a nog go.
for non async implementations that need to return a task you can return something like
Task.FromResult<T>orTask.CompletedTask. This will not block.See also await Task.CompletedTask for what?
To summarize: the default implementation does not do anything async but derived classes can without having to change the method signature.