Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between connection.OpenAsync and connection.Open when using Dapper QueryAsync method

What is the difference between using connection.OpenAsync() and connection.Open() when using dapper's QueryAsync method.

Async:

public async Task<IList<Product>> GetListAsync()
    {
        using (var connection = new SqlConnection(_connectionString))
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendLine("SELECT Id, Name ");
            sql.AppendLine("FROM Product ");

            await connection.OpenAsync();
            var tickets = await connection.QueryAsync<Ticket>(sql.ToString());
            return tickets.ToList();
        }
    }

Not Async:

public async Task<IList<Product>> GetListAsync()
{
    using (var connection = new SqlConnection(_connectionString))
    {
        StringBuilder sql = new StringBuilder();
        sql.AppendLine("SELECT Id, Name ");
        sql.AppendLine("FROM Product ");

        connection.Open();
        var tickets = await connection.QueryAsync<Ticket>(sql.ToString());
        return tickets.ToList();
    }
}
like image 520
Blake Rivell Avatar asked Oct 18 '17 02:10

Blake Rivell


2 Answers

OpenAsync() will return immdiately from the method (GetListAsync) to the method that called it so the thread can be free to do other things in the meantime. For example, lets say it takes one second to open the connection (just for example), then the thread can do something else. The opening of the connection will not be done by the thread that calls it.

Once the connection is opened, the exécution will go to the next line which is:

var tickets = await connection.QueryAsync<Ticket>(sql.ToString());

Note: Please note in some cases if IsCompleted returns true then it will be done synchronously.

like image 179
CodingYoshi Avatar answered Oct 01 '22 15:10

CodingYoshi


According to source code for Open and OpenAsync for DbConnection,

abstract public void Open();

public Task OpenAsync() {
    return OpenAsync(CancellationToken.None);
}

public virtual Task OpenAsync(CancellationToken cancellationToken) {
    TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>();

    if (cancellationToken.IsCancellationRequested) {
        taskCompletionSource.SetCanceled();
    }
    else {
        try {
            Open();
            taskCompletionSource.SetResult(null);
        }
        catch (Exception e) {
            taskCompletionSource.SetException(e);
        }
    }

    return taskCompletionSource.Task;
}

OpenAsync is just to allow for async code to be awaited while not blocking the thread.

Now with Dapper you do not necessarily have to open the connection as internally the method would open the connection if it is closed.

like image 42
Nkosi Avatar answered Oct 01 '22 15:10

Nkosi