繁体   English   中英

SQL 超时已过。 操作完成前超时时间已过或服务器未响应

[英]SQL Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding

我正在使用Microsoft.EntityFrameworkCore.SqlServer 2.2.6。 我有一个存储过程,通常需要 1 到 2 秒才能执行。

我正在使用 .NET Core 2.2 和 EF Core 来执行该存储过程。

appsettings.json

{  
    "SqlCommandTimeout": 120, // seconds
    "ConnectionStrings": {
        "DefaultConnection": "Server=serverip;Database=MyDataBase;Integrated Security=True;"
    }
}

startup.cs我正在设置连接字符串和超时

var sqlCommandTimeout = configuration.GetValue<int>("SqlCommandTimeout");
services.AddDbContext<MyDBContext>(options =>
        {
            options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
                sqlServerOptions => sqlServerOptions.CommandTimeout(sqlCommandTimeout));
        });

此代码执行存储过程并填充 DTO:

public static async Task<IEnumerable<AvailableWorkDTO>> prcGetAvailableWork(this MyDBContext dbContext, int userID)
{            
    var timeout = dbContext.Database.GetCommandTimeout() ?? 120;

    var result = new List<AvailableWorkDTO>();

    using (var cmd = dbContext.Database.GetDbConnection().CreateCommand())
    {
        var p1 = new SqlParameter("@UserID", SqlDbType.Int)
            {
                Value = userID
            };

        cmd.CommandText = "dbo.prcGetAvailableWork";
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Add(p1);
        cmd.CommandTimeout = timeout;

        await dbContext.Database.OpenConnectionAsync().ConfigureAwait(false);

        using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false))
        {
            while (await reader.ReadAsync().ConfigureAwait(false))
            {
                var item = new AvailableWorkDTO();
                item.ID = reader.GetInt32(0);
                item.Name = reader.GetString(1);
                item.Title = reader.GetString(2);
                item.Count = reader.GetInt32(3);

                result.Add(item);
            }
        }
    }

    return result;
}

存储过程仅使用READUNCOMMITTED隔离级别从几个表中读取数据。 然而,还有另一个后台进程每 3 分钟将新记录插入这些表中。

问题

时不时地,当用户数量增加时,我们会看到超时异常。

System.Data.SqlClient.SqlException (0x80131904): 超时已过。

在操作完成之前超时期限已过,或者服务器没有响应。

System.ComponentModel.Win32Exception (258): 等待操作超时
在 System.Data.SqlClient.SqlCommand.<>c.b__122_0(任务1 result) at System.Threading.Tasks.ContinuationResultTaskFromResultTask 2.InnerInvoke()
在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback 回调,Object 状态)

--- 从抛出异常的先前位置开始的堆栈跟踪结束 ---

在 System.Threading.Tasks.Task.ExecuteWithThreadLocal(任务和 currentTaskSlot)

--- 从抛出异常的先前位置开始的堆栈跟踪结束 ---

在 D:\Jenkins\xx-production\workspace\Src\Common\Data\Entities\StoredProcedures\StoredPrcedureExtensions.cs 中的 Data.Entities.StoredProcedures.StoredPrcedureExtensions.prcGetAvailableWork(MyDbContext dbContext,Int32 用户 ID):第 56 行
在....
....
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper 映射器,ObjectMethodExecutor 执行器,Object controller,对象 [] 参数)

在 System.Threading.Tasks.ValueTask`1.get_Result()
在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext 上下文)
在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next,Scope& scope,Object& state,Boolean& isCompleted)
在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
在 Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
在 Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext 上下文)
在 Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next,Scope& scope,Object& state,Boolean& isCompleted)
在 Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
在 Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
在 Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
在 Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext 上下文)
在 Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext 上下文)
在 Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext 上下文)
ClientConnectionId:c10da510-509f-4bfb-8b37-58c0ee8fa3b1
错误号:-2,State:0,Class:11at

问题

  1. 我正在使用 EF Core 2.2。 根据文档,对于某些异步方法, SqlCommand.CommandTimeout属性被忽略。 在上面的代码中,超时会被忽略吗?

  2. SQL Server Profiler 显示存储过程实际上仅通过await cmd.ExecuteReaderAsync()行执行一次。 然而,我们仍然需要在阅读阅读器时保持连接打开。 CommandTimeOut是否包括从阅读器读取所需的时间?

  3. 最多 100 个用户可以并发访问此存储过程。 我们会仔细检查索引,并且每天都会执行预定的索引工作。 我们正在使用

     Microsoft SQL Server 2017 (RTM-CU13) (KB4466404) - 14.0.3048.4 (X64) Standard Edition (64-bit)

    在 Windows Server 2019 上。它应该能够处理负载。 有没有我们需要查看的设置? (SQL Server 也有多个其他数据库)

在上面的代码中超时会被忽略吗?

不。

System.Data.SqlClient.SqlException (0x80131904): Timeout expired.

这是由 CommandTimeout 引起的客户端超时。

CommandTimeOut 是否包括从阅读器读取所需的时间?

是的。 根据文档, SqlCommand.CommandTimeout 包括 SqlDataReader.Read() 时间。

有什么我们需要看的设置吗?

打开查询存储并跟踪会话等待统计信息,以查看您是否看到阻塞、CPU 争用或其他情况。

我也有同样的问题,在我的例子中,我用以下方式编写了存储过程代码

BEGIN TRAN
BEGIN TRY
  some code here....
 --COMMIT TRAN // it is missed or written in the wrong place
END TRY

存储过程代码中缺少“COMMIT TRAN”代码,但存在“BEGIN TRAN” ,因为之前的调用正在等待 state 并且下一个事务服务器不会响应

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM