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

余生长醉 提交于 2019-12-23 14:55:34

问题


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();
    }
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/46801943/difference-between-connection-openasync-and-connection-open-when-using-dapper-qu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!