Let*_*nch 4 c# sql connection-timeout dapper
我们遇到了一个问题,即我们使用 Dapper async 一次执行大量查询(大量为 100-200),最终出现超时异常。我认为正在发生的事情是 Dapper 正在做的事情await ... [connection].OpenAsync(...)(参见此处)允许其他异步代码也打开连接,然后当代码返回到原始打开的连接以启动时,他查询 sql 超时已经过去了。我的问题是有一种方法或做法可以防止这种情况发生。我们考虑的一种解决方案是增加 sql 超时。另一个是减少我们一次从数据库查询的对象数量。然而,感觉我们做得不对,想联系一下看看是否有更好的方法。提前致谢,抱歉,如果这是重复的,我找不到任何其他描述此问题的解决方案。
这是执行查询的代码:
public async Task<bool> ThingExistsAsync(int? somethingId, int somethingTypeId)
{
using (var conn = connectionFactory.GetEddsPerformanceConnection())
{
return await conn.QueryFirstOrDefaultAsync<int>(Resources.Event_ReadCountBySomethingTypeAndId,
new { somethingId, somethingTypeId }) > 0;
}
}
Run Code Online (Sandbox Code Playgroud)
调用代码:
Task.WhenAll(listOfThings.Select(t => ThingExistsAsync(t.Id, t.Type)));
Run Code Online (Sandbox Code Playgroud)
这是例外情况:
System.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__174_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Dapper.SqlMapper.<QueryRowAsync>d__24`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Company.Product.Data.Repositories.ThingRepository.<ThingExistsAsync>d__17.MoveNext()
...
ClientConnectionId:059604ea-1123-4d8d-ba00-071ed3a0b962
Error Number:-2,State:0,Class:11
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的问题。我的 SqlConnection 对象指定了连接超时,但简洁的查询不支持它,因此我传递了连接的超时值,但当然您可以传递任何您想要的值。
这是我为解决问题所做的操作:
var result = await conn.QueryAsync(sqlQueryText, new { param = "paramValue" }, commandTimeout: conn.ConnectionTimeout);
Run Code Online (Sandbox Code Playgroud)