问题
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