connection.OpenAsync和connection.Open之间的区别在使用Dapper QueryAsync方法时

时间:2017-10-18 02:33:07

标签: c# asp.net sql-server dapper sqlconnection

使用dapper的QueryAsync方法时,使用connection.OpenAsync()和connection.Open()有什么区别。

异步:

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

非异步:

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

2 个答案:

答案 0 :(得分:3)

OpenAsync()将从方法(GetListAsync)中不可避免地返回到调用它的方法,以便线程可以在此期间自由地执行其他操作。例如,假设打开连接需要一秒钟(例如),然后线程可以执行其他操作。连接的打开不会由调用它的线程完成。

一旦打开连接,exécution将转到下一行:

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

注意:请注意,如果IsCompleted返回true,则会同步完成。

答案 1 :(得分:2)

根据Open的{​​{3}}和OpenAsync的{​​{1}},

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; } 只是为了在不阻塞线程时允许等待异步代码。

现在使用Dapper你不一定要在内部打开连接,如果关闭,方法会打开连接。