我注意到在Dapper.NET中使用异步API时,我没有遵守我在扩展方法中传递的命令超时值。 然后我遇到了SqlCommand.CommandTimeout的MSDN documentation,似乎这不是“支持”的。
在异步方法期间将忽略CommandTimeout属性 诸如BeginExecuteReader之类的调用。
我在基类中使用以下方法。
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在超时间隔内断开连接并处理连接?
答案 0 :(得分:0)
这是一个在当前版本的Dapper中从异步方法调用的函数。正如您所看到的那样,CommandTimeout已经得到了很好的尊重。
internal IDbCommand SetupCommand(IDbConnection cnn, Action<IDbCommand, object> paramReader)
{
IDbCommand command = cnn.CreateCommand();
Action<IDbCommand> init = CommandDefinition.GetInit(command.GetType());
if (init != null)
init(command);
if (this.Transaction != null)
command.Transaction = this.Transaction;
command.CommandText = this.CommandText;
if (this.CommandTimeout.HasValue)
{
command.CommandTimeout = this.CommandTimeout.Value;
}
else
{
int? commandTimeout = SqlMapper.Settings.CommandTimeout;
if (commandTimeout.HasValue)
{
IDbCommand dbCommand = command;
commandTimeout = SqlMapper.Settings.CommandTimeout;
int num = commandTimeout.Value;
dbCommand.CommandTimeout = num;
}
}
System.Data.CommandType? commandType = this.CommandType;
if (commandType.HasValue)
{
IDbCommand dbCommand = command;
commandType = this.CommandType;
int num = (int) commandType.Value;
dbCommand.CommandType = (System.Data.CommandType) num;
}
if (paramReader != null)
paramReader(command, this.Parameters);
return command;
}
答案 1 :(得分:0)
令人烦恼的是,SqlClient确实处理了这个问题!但是,我想知道你是否可以做一些涉及的事情:
稍微丑陋,如果数据库提供商本身不尊重超时,这可能是图书馆应该封装的内容。干净地取消正在运行的命令可能还需要执行其他步骤,在这种情况下,可能仅库可以正确执行此操作(因为只有库可以访问命令)