Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is TaskCanceledException thrown when using Dapper QueryAsync<T> without async/await?

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.

like image 308
Brandon Avatar asked Sep 01 '16 19:09

Brandon


1 Answers

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.

like image 111
Stephen Cleary Avatar answered Sep 29 '22 00:09

Stephen Cleary