I am reading a book "Terrell R. - Concurrency in .NET".
There is a nice code example:
Lazy<Task<Person>> person = new Lazy<Task<Person>>(
async () =>
{
using (var cmd = new SqlCommand(cmdText, conn))
using (var reader = await cmd.ExecuteReaderAsync())
{
// some code...
}
});
async Task<Person> FetchPerson()
{
return await person.Value;
}
The author said:
Because the lambda expression is asynchronous, it can be executed on any thread that calls Value, and the expression will run within the context.
As i understand it, the Thread come to FetchPerson and is stuck in Lamda execution. Is that realy bad? What consequences?
As a solution, the author suggest to create a Task:
Lazy<Task<Person>> person = new Lazy<Task<Person>>(
() => Task.Run(
async () =>
{
using (var cmd = new SqlCommand(cmdText, conn))
using (var reader = await cmd.ExecuteReaderAsync())
{
// some code...
}
}));
Is that really correct? This is an IO operation, but we steal CPU thread from Threadpool.