我注意到在Dapper.NET中使用异步API时,我传递给扩展方法的命令超时值没有得到尊重。然后我发现SqlCommand.CommandTimeout的MSDN文档,似乎这是一些不被“支持”的东西。
我在基类中使用以下方法。在诸如BeginExecuteReader之类的异步方法调用期间,CommandTimeout属性将被忽略。
public async Task<int> ExecuteAsync(string sql, object param = null,
CommandType commandType = CommandType.Text, int? commandTimeout = null, IDbTransaction transaction = null)
{
using (var connection = Connection)
{
Task<int> queryTask = connection.ExecuteAsync(sql, param, transaction, commandTimeout ?? CommandTimeoutDefault, commandType);
int result = await queryTask.ConfigureAwait(false);
connection.Close();
connection.Dispose();
return result;
}
}
public async Task<IEnumerable<TEntity>> QueryAsync(string sql, object param = null,
CommandType commandType = CommandType.Text, int? commandTimeout = null, IDbTransaction transaction = null)
{
using (var connection = Connection)
{
Task<IEnumerable<TEntity>> queryTask = connection.QueryAsync<TEntity>(sql, param, transaction, commandTimeout ?? CommandTimeoutDefault, commandType);
IEnumerable<TEntity> data = await queryTask.ConfigureAwait(false);
connection.Close();
connection.Dispose();
return data;
}
}
假设 CommandTimeoutDefault
是30,我可以看到一个请求花费50秒仍然会被评估。
有没有想法如何使用异步的 Dapper.NET API 在超时时间内断开并处理连接?
using
完成了这些操作。 - Marc Gravell