Why does calling .Result
on this method result in a TaskCanceledException:
public Task<IEnumerable<object>> GetAsync()
{
using (var conn = new SqlConnection("connectionString"))
{
return conn.QueryAsync<object>("select * from objects");
}
}
But calling .Result
on this method works:
public async Task<IEnumerable<object>> GetAsync()
{
using (var conn = new SqlConnection("connectionString"))
{
return await conn.QueryAsync<object>("select * from objects");
}
}
The difference being the async\await
keywords are being used in the second method.
The first method starts the query (calls QueryAsync
), then it disposes the SqlConnection
, and then it returns the task representing that query. The task is canceled because the SqlConnection
was disposed before it could complete.
The second method starts the query (calls QueryAsync
), asynchronously waits for that query to complete, and then disposes the SqlConnection
. The task returned from the second method represents the completion of that method.
For more information on async
/await
, see my blog.
On a side note, you should not consume asynchronous methods with Result
; you should use await
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With