使用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();
}
}
答案 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你不一定要在内部打开连接,如果关闭,方法会打开连接。