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

标签 entity-framework asp.net-core entity-framework-core sql-server-2014 ef-core-2.2

我正在使用 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): Timeout expired.

The timeout period elapsed prior to completion of the operation or the server is not responding.

System.ComponentModel.Win32Exception (258): The wait operation timed out
at System.Data.SqlClient.SqlCommand.<>c.b__122_0(Task1 result) at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)

--- End of stack trace from previous location where exception was thrown ---

at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)

--- End of stack trace from previous location where exception was thrown ---

at Data.Entities.StoredProcedures.StoredPrcedureExtensions.prcGetAvailableWork(MyDbContext dbContext, Int32 userID) in D:\Jenkins\xx-production\workspace\Src\Common\Data\Entities\StoredProcedures\StoredPrcedureExtensions.cs:line 56
at ....
....
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)

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

问题

  1. 我正在使用 EF Core 2.2。基于documentation ,对于某些异步方法, 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也有多个其他数据库)

最佳答案

In the above code will the timeout ignored?

没有。

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

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

Is the CommandTimeOut includes time takes for reading from the reader?

是的。每docs , SqlCommand.CommandTimeout 包括 SqlDataReader.Read() 时间。

Is there any settings that we need to look?

打开 Query Store并跟踪 session wait stats查看您是否看到阻塞、CPU 争用或其他问题。

关于entity-framework - SQL 超时已过期。操作完成前超时时间已过或服务器未响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69681044/

相关文章:

entity-framework - 如何在 EF4 中获取实体的第一个 EntityKey 名称

asp.net - 在 ASP.NET 应用程序中,DbContext 存储在哪里?

c# - 如果需要同时批量处理事务和异步执行事务,是否应该将EF6 DbContext作为作用域或临时注入(inject)?

c# - WebAPI : Creating custom BadRequest status outside of ApiController

c# - 在 Entity Framework Core 支持中始终加密

c# - Entity Framework MariaDb 日期作为字符串问题

c# - 安全访问部分属性

.net - 使用 Autofac LifeTimeScope 和 Asp.net Core DI Extension IServiceScopeFactory 创建范围之间的区别

c# - 使用配置调用了 AddDbContext,但是上下文类型 'ContextClass' 只声明了一个无参数构造函数?

asp.net - Entity Framework Core 中的两个外键