超时已过。操作完成之前超时时间已过,或者服务器未响应。该声明已终止

发布于 2024-12-22 14:15:15 字数 3500 浏览 3 评论 0原文

我的网站有很多用户(每天20000-60000),这是一个移动文件下载网站。我可以远程访问我的服务器(Windows Server 2008-R2)。
我之前收到过“服务器不可用”错误,但现在我看到连接超时错误。
我对此不熟悉 - 为什么会发生这种情况以及如何修复它?

完整的错误如下:

“/”应用程序中的服务器错误。超时已过。超时时间 操作完成之前已过去或服务器未完成 回应。该声明已终止。描述:安 当前网页执行期间发生未处理的异常 要求。请查看堆栈跟踪以获取有关的更多信息 错误及其在代码中的起源。

异常详细信息:System.Data.SqlClient.SqlException:超时 已到期。超时时间在完成之前已过 操作或服务器没有响应。该声明已 终止。

来源错误:

执行过程中产生了未处理的异常 当前的网络请求。有关原产地和地点的信息 可以使用下面的异常堆栈跟踪来识别异常。

堆栈跟踪:

[SqlException (0x80131904):超时已过期。超时时间 操作完成之前已过去或服务器未完成 回应。该声明已终止。]
System.Data.SqlClient.SqlConnection.OnError(SqlException异常, 布尔中断连接)+404
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +412
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler、SqlDataReader 数据流、 BulkCopySimpleResultSet BulkCopyHandler、TdsParserStateObject stateObj) +1363
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior,字符串resetOptionsString)+6387741
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior、RunBehavior runBehavior、布尔值 returnStream、布尔值 异步)+6389442
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior、RunBehavior runBehavior、布尔值 returnStream、字符串 方法,DbAsyncResult 结果)+538
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult 结果,字符串方法名称,布尔值 sendToPipe) +689
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +327
NovinMedia.Data.DbObject.RunProcedure(字符串storedProcName, IDataParameter[]参数,Int32&受影响的行)+209
DataLayer.OnlineUsers.Update_SessionEnd_And_Online(对象Session_End, 布尔在线)+440
NiceFileExplorer.Global.Application_Start(对象发送者,EventArgs e) +163

[HttpException (0x80004005):超时已过期。超时时间 操作完成之前已过去或服务器未完成 回应。该声明已终止。]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext 上下文,HttpApplication 应用程序)+405205​​3
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext、HttpContext 上下文、MethodInfo[] 处理程序)+191
System.Web.HttpApplication.InitSpecial(HttpApplicationState状态, MethodInfo[] 处理程序、IntPtr appContext、HttpContext 上下文)+352
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext、HttpContext 上下文)+407
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr 应用上下文)+375

[HttpException (0x80004005):超时已过期。超时时间 操作完成之前已过去或服务器未完成 回应。该声明已终止。]
System.Web.HttpRuntime.FirstRequestInit(HttpContext上下文)+11686928 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext上下文) +141 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr,HttpContext 上下文)+4863749


回答后编辑:
我的 Global.asax 中的 Application_Start 如下所示:

protected void Application_Start(object sender, EventArgs e)
{
    Application["OnlineUsers"] = 0;

    OnlineUsers.Update_SessionEnd_And_Online(
        DateTime.Now,
        false);

    AddTask("DoStuff", 10);
}

被调用的存储过程是:

ALTER Procedure [dbo].[sp_OnlineUsers_Update_SessionEnd_And_Online]
    @Session_End datetime,
    @Online bit
As
Begin
    Update OnlineUsers
    SET
        [Session_End] = @Session_End,
        [Online] = @Online

End

我有两种获取在线用户的方法:

  1. 使用 Application["OnlineUsers"] = 0;
  2. 另一个使用数据库

因此,对于方法#2,我在 Application_Start 处重置了所有 OnlineUsers。该表中有超过 482,751 条记录。

I have many users on my web site (20000-60000 per day), which is a download site for mobile files. I have remote access to my server (windows server 2008-R2).
I've received "Server is unavailable" errors before, but I am now seeing a connection timeout error.

I'm not familiar with this - why does it occur and how can I fix it?

The full error is below:

Server Error in '/' Application. Timeout expired. The timeout period
elapsed prior to completion of the operation or the server is not
responding. The statement has been terminated. Description: An
unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Timeout
expired. The timeout period elapsed prior to completion of the
operation or the server is not responding. The statement has been
terminated.

Source Error:

An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.

Stack Trace:

[SqlException (0x80131904): Timeout expired. The timeout period
elapsed prior to completion of the operation or the server is not
responding. The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection) +404
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +412
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj) +1363
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) +6387741
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async) +6389442
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, DbAsyncResult result) +538
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult
result, String methodName, Boolean sendToPipe) +689
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +327
NovinMedia.Data.DbObject.RunProcedure(String storedProcName,
IDataParameter[] parameters, Int32& rowsAffected) +209
DataLayer.OnlineUsers.Update_SessionEnd_And_Online(Object Session_End,
Boolean Online) +440
NiceFileExplorer.Global.Application_Start(Object sender, EventArgs e)
+163

[HttpException (0x80004005): Timeout expired. The timeout period
elapsed prior to completion of the operation or the server is not
responding. The statement has been terminated.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext
context, HttpApplication app) +4052053
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
appContext, HttpContext context, MethodInfo[] handlers) +191
System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
MethodInfo[] handlers, IntPtr appContext, HttpContext context) +352
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
appContext, HttpContext context) +407
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
appContext) +375

[HttpException (0x80004005): Timeout expired. The timeout period
elapsed prior to completion of the operation or the server is not
responding. The statement has been terminated.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11686928
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
+141 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
wr, HttpContext context) +4863749


EDIT AFTER ANSWERS:
my Application_Start in Global.asax is like below:

protected void Application_Start(object sender, EventArgs e)
{
    Application["OnlineUsers"] = 0;

    OnlineUsers.Update_SessionEnd_And_Online(
        DateTime.Now,
        false);

    AddTask("DoStuff", 10);
}

The stored procedure being called is:

ALTER Procedure [dbo].[sp_OnlineUsers_Update_SessionEnd_And_Online]
    @Session_End datetime,
    @Online bit
As
Begin
    Update OnlineUsers
    SET
        [Session_End] = @Session_End,
        [Online] = @Online

End

I have two methods for getting online users:

  1. using Application["OnlineUsers"] = 0;
  2. the other one using database

So, for method #2 I reset all OnlineUsers at Application_Start. There are over 482,751 records in that table.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(26

那些过往 2024-12-29 14:15:15

看起来您的查询花费的时间比应有的时间长。
从堆栈跟踪和代码中,您应该能够准确确定那是什么查询。

这种类型的超时可能有三个原因:

  1. 某处出现死锁
  2. 数据库的统计信息和/或查询计划缓存不正确
  3. 查询太复杂,需要调整

死锁可能很难修复,但很容易确定是否是这种情况。使用 Sql Server Management Studio 连接到您的数据库。在左侧窗格中,右键单击服务器节点并选择“活动监视器”。查看正在运行的进程。
通常大多数会处于空闲或运行状态。当问题发生时,您可以通过进程状态识别任何被阻止的进程。如果您右键单击该进程并选择详细信息,它将显示该进程执行的最后一个查询。

第二个问题将导致数据库使用次优的查询计划。可以通过清除统计信息来解决:

exec sp_updatestats

如果这不起作用,您也可以尝试

dbcc freeproccache

在服务器负载较重时不应该这样做,因为它会暂时导致性能下降,因为所有存储过程和查询在第一次时都会重新编译被执行。
但是,由于您指出问题有时会发生,并且堆栈跟踪表明您的应用程序正在启动,因此我认为您正在运行一个仅偶尔运行的查询。强制 SQL Server 不要重用以前的查询计划可能会更好。有关如何执行此操作的详细信息,请参阅此答案

我已经谈到了第三个问题,但是您可以通过手动执行查询(例如使用 Sql Server Management Studio)轻松确定查询是否需要调整。如果查询需要很长时间才能完成,即使在重置统计信息之后,您可能也需要对其进行调整。如需帮助,您应该在新问题中发布确切的查询。

Looks like you have a query that is taking longer than it should.
From your stack trace and your code you should be able to determine exactly what query that is.

This type of timeout can have three causes;

  1. There's a deadlock somewhere
  2. The database's statistics and/or query plan cache are incorrect
  3. The query is too complex and needs to be tuned

A deadlock can be difficult to fix, but it's easy to determine whether that is the case. Connect to your database with Sql Server Management Studio. In the left pane right-click on the server node and select Activity Monitor. Take a look at the running processes.
Normally most will be idle or running. When the problem occurs you can identify any blocked process by the process state. If you right-click on the process and select details it'll show you the last query executed by the process.

The second issue will cause the database to use a sub-optimal query plan. It can be resolved by clearing the statistics:

exec sp_updatestats

If that doesn't work you could also try

dbcc freeproccache

You should not do this when your server is under heavy load because it will temporarily incur a big performace hit as all stored procs and queries are recompiled when first executed.
However, since you state the issue occurs sometimes, and the stack trace indicates your application is starting up, I think you're running a query that is only run on occasionally. You may be better off by forcing SQL Server not to reuse a previous query plan. See this answer for details on how to do that.

I've already touched on the third issue, but you can easily determine whether the query needs tuning by executing the query manually, for example using Sql Server Management Studio. If the query takes too long to complete, even after resetting the statistics you'll probably need to tune it. For help with that, you should post the exact query in a new question.

寄意 2024-12-29 14:15:15

在运行存储过程的代码中,应该有类似这样的内容:

SqlCommand c = new SqlCommand(...)
//...

添加这样一行代码:

c.CommandTimeout = 0;

这将等待操作完成所需的时间。

In your code where you run the stored procedure you should have something like this:

SqlCommand c = new SqlCommand(...)
//...

Add such a line of code:

c.CommandTimeout = 0;

This will wait as much time as needed for the operation to complete.

三生殊途 2024-12-29 14:15:15

您可以设置 SQL 命令的 CommandTimeout 属性以允许长时间运行 SQL 事务。

您可能还需要查看导致超时的 SQL 查询。

You could set the CommandTimeout property of the SQL Command to allow for the long running SQL transaction.

You might also need to look at the SQL Query that is causing the timeout.

少钕鈤記 2024-12-29 14:15:15

我遇到了同样的问题,并通过在 web.config 文件中添加“连接时间”值来解决。找到连接字符串并添加 Connection Timeout=3600"

这是示例

  <connectionStrings>
    <add name="MyConn" providerName="System.Data.SqlClient" connectionString="Data Source=MySQLServer;Initial Catalog=MyDB;User ID=sa;Password=123;Connection Timeout=3600" />
  </connectionStrings>

I had the same issue and resolved by adding "Connection Time" value in web.config file. locate the connectionStrings and add Connection Timeout=3600"

here is the sample

  <connectionStrings>
    <add name="MyConn" providerName="System.Data.SqlClient" connectionString="Data Source=MySQLServer;Initial Catalog=MyDB;User ID=sa;Password=123;Connection Timeout=3600" />
  </connectionStrings>
与风相奔跑 2024-12-29 14:15:15

也许这对某人有用。
我遇到了同样的问题,在我的例子中,原因是 SqlConnection 已打开,并且未在我在循环中调用的方法中释放,并进行了大约 2500 次迭代。连接池已耗尽。正确处理就解决了这个问题。

Maybe it will be useful for somebody.
I faced with the same problem and in my case the reason was the SqlConnection was opened and not disposed in the method that I called in loop with about 2500 iterations. Connection pool was exhausted. Proper disposing solved the problem.

养猫人 2024-12-29 14:15:15

您必须设置 CommandTimeout 属性。您可以在 DbContext 子类中设置 CommandTimeout 属性。

public partial class StudentDatabaseEntities : DbContext
{
    public StudentDatabaseEntities()
        : base("name=StudentDatabaseEntities")
    {
        this.Database.CommandTimeout = 180;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<StudentDbTable> StudentDbTables { get; set; }
}

You have to set CommandTimeout attribute. You can set the CommandTimeout attribute in DbContext child class.

public partial class StudentDatabaseEntities : DbContext
{
    public StudentDatabaseEntities()
        : base("name=StudentDatabaseEntities")
    {
        this.Database.CommandTimeout = 180;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<StudentDbTable> StudentDbTables { get; set; }
}
萤火眠眠 2024-12-29 14:15:15

虽然所有早期的回复都解决了这个问题,但它们并未涵盖所有情况。

Microsoft 已承认该问题,并于 2011 年针对受支持的操作系统修复了该问题,因此,如果您得到如下堆栈跟踪:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)

您可能需要更新您的 .NET 程序集。

出现此问题的原因是连接重试时出错
镜像数据库的算法。

当使用重试算法时,数据提供者等待
首先读取(SniReadSync)调用来完成。呼叫将发送至
运行SQL Server的后端计算机,等待时间为
通过将连接超时值乘以 0.08 计算得出。
然而,数据提供者错误地设置了与注定失败的连接
说明响应是否缓慢以及第一个 SniReadSync 调用是否缓慢
在等待时间结束之前完成。

有关详细信息,请参阅知识库文章 2605597

https://support.microsoft.com/kb/2605597

While all the earlier responses address the issue they did not cover all cases.

Microsoft has acknowledged the issue and fixed it in 2011 for supported operating systems, so if you get the stack trace like:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)

you may need to update your .NET assemblies.

This issue occurs because of an error in the connection-retry
algorithm for mirrored databases.

When the retry-algorithm is used, the data provider waits for the
first read (SniReadSync) call to finish. The call is sent to the
back-end computer that is running SQL Server, and the waiting time is
calculated by multiplying the connection time-out value by 0.08.
However, the data provider incorrectly sets a connection to a doomed
state if a response is slow and if the first SniReadSync call is not
completed before the waiting time expires.

See KB 2605597 for details

https://support.microsoft.com/kb/2605597

热鲨 2024-12-29 14:15:15

如果您使用带有 Startup.cs 约定的 ASP.NET Core,您可以像这样访问和设置查询命令超时选项:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool<MyDbContext>(_ =>
    {
        _.UseSqlServer(Configuration.GetConnectionString("MyConnectionString"), options => 
        {
            options.CommandTimeout(180); // 3 minutes
        });
    });
}

If you are using ASP.NET Core with the Startup.cs convention, you can access and set the query command timeout option like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool<MyDbContext>(_ =>
    {
        _.UseSqlServer(Configuration.GetConnectionString("MyConnectionString"), options => 
        {
            options.CommandTimeout(180); // 3 minutes
        });
    });
}
马蹄踏│碎落叶 2024-12-29 14:15:15

我遇到了同样的问题,花了大约三天的时间。我注意到,由于我们的记录数量不多,我们的高级开发人员在数据库中保留了 2 张图像和指纹。当我尝试获取这个十六进制值时,它需要很长时间,我计算出执行程序的平均时间约为 38 秒。默认命令超时为 30 秒,因此低于运行存储过程所需的平均时间。我将命令超时设置如下

cmd.CommandTimeout = 50

,它工作正常,但有时如果您的查询花费超过 50 秒,它会提示相同的错误。

I faced same problem worked on it around 3 days. I noticed as our number of records are not much our senior developer keeps 2 images and Fingerprint in database. When I try to fetch this hex values it taking long time, I calculate average time to execute my procedure its around 38 seconds. The default commandtimeout is 30 seconds so its less than average time required to run my stored procedure. I set my commandtimeout like below

cmd.CommandTimeout = 50

and its working fine but sometimes if your query takes more than 50 seconds it will prompt same error.

素食主义者 2024-12-29 14:15:15

我最近遇到了这个错误,经过一些简短的调查,发现原因是我们保存数据库的磁盘空间不足(小于 1GB)。

一旦我将数据库文件(.mdf 和 .ldf)移至同一服务器上的另一个磁盘(有更多空间),同一页面(运行查询)就会在三秒内加载超时。

在尝试解决此错误时,需要调查的另一件事是数据库日志文件的大小。您的日志文件可能只需要缩小。

I encountered this error recently and after some brief investigation, found the cause to be that we were running out of space on the disk holding the database (less than 1GB).

As soon as I moved out the database files (.mdf and .ldf) to another disk on the same server (with lots more space), the same page (running the query) that had timed-out loaded within three seconds.

One other thing to investigate, while trying to resolve this error, is the size of the database log files. Your log files just might need to be shrunk.

给我一枪 2024-12-29 14:15:15

默认超时为 15 秒,更改为 0 表示无限制,任何其他数字都是秒数。

代码中

using (SqlCommand sqlCmd = new SqlCommand(sqlQueryString, sqlConnection))
   {
      sqlCmd.CommandTimeout = 0; // 0 = give it as much time as it needs to complete
      ...
    }

在 Web.Config 的 ,“Command Timeout=0;”不要超时,或者低于1小时(3600秒)

  <add name="ConnectionString" connectionString="Data Source=ServerName;User ID=UserName;Password=Password;Command Timeout=3600;" providerName="System.Data.SqlClient" />

Default timeout is 15 seconds, to change that, 0 is unlimited, any other number is the number of seconds.

In Code

using (SqlCommand sqlCmd = new SqlCommand(sqlQueryString, sqlConnection))
   {
      sqlCmd.CommandTimeout = 0; // 0 = give it as much time as it needs to complete
      ...
    }

In Your Web.Config, "Command Timeout=0;" do not time out, or as below 1 hour (3600 seconds)

  <add name="ConnectionString" connectionString="Data Source=ServerName;User ID=UserName;Password=Password;Command Timeout=3600;" providerName="System.Data.SqlClient" />
毁梦 2024-12-29 14:15:15

我在 sp_foo 中遇到大量计算问题,需要很长时间,所以我修复了
用这个小代码

public partial class FooEntities : DbContext
{
   public FooEntities()
         : base("name=FooEntities")
    {
        this.Configuration.LazyLoadingEnabled = false;

        // Get the ObjectContext related to this DbContext
        var objectContext = (this as IObjectContextAdapter).ObjectContext;

        // Sets the command timeout for all the commands
        objectContext.CommandTimeout = 380;
    }

I have issue with large calculation in sp_foo that take large time so i fixed
with this little bit code

public partial class FooEntities : DbContext
{
   public FooEntities()
         : base("name=FooEntities")
    {
        this.Configuration.LazyLoadingEnabled = false;

        // Get the ObjectContext related to this DbContext
        var objectContext = (this as IObjectContextAdapter).ObjectContext;

        // Sets the command timeout for all the commands
        objectContext.CommandTimeout = 380;
    }
夜血缘 2024-12-29 14:15:15

TLDR

  1. 在数据量、网络设置和代码未更改的情况下,重新启动应用程序和数据库服务器是最快的修复方法。我们总是这样做作为一项规则
  2. 可能是硬盘驱动器出现故障需要更换的指标 - 检查系统通知

我经常因为各种原因遇到此错误,并有各种解决方案,包括:

  1. 重构我的代码以使用 SqlBulkCopy
  2. 增加超时值,如各种中所述答案或检查
    根本原因(可能与数据无关
  3. 连接超时(默认 15 秒) - 在终止之前等待与 SQL Server 建立连接需要多长时间 - TCP/PORT 相关 - 可以通过疑难解答checklist(非常方便的 MSDN 文章)
  4. 命令超时(默认 30 秒) - 等待执行查询需要多长时间 - 查询执行/网络流量相关 - 还有一个故障排除过程(另一个非常方便的 MSDN 文章)
  5. 重新启动服务器 - 应用程序和服务器数据库服务器(如果单独) - 代码和数据未更改,环境必须已更改 - 您必须做的第一件事。通常由补丁(操作系统、.Net Framework 或 SQL Server 补丁或更新)引起。特别是如果出现如下超时异常(即使我们不使用Azure):
    • System.Data.Entity.Core.EntityException:已引发异常,可能是由于暂时性故障所致。如果要连接到 SQL Azure 数据库,请考虑使用 SqlAzureExecutionStrategy。 ---> System.Data.Entity.Core.EntityCommandExecutionException:执行命令定义时发生错误。有关详细信息,请参阅内部异常。 ---> System.Data.SqlClient.SqlException:从服务器接收结果时发生传输级错误。 (提供者:TCP 提供者,错误:0 - 信号量超时期限已过期。) ---> System.ComponentModel.Win32Exception:信号量超时期限已过期

TLDR:

  1. Rebooting both application and DB servers is the quickest fix where data volume, network settings and code haven't changed. We always do so as a rule
  2. May be indicator of failing hard-drive that needs replacement - check system notifications

I have often encountered this error for various reasons and have had various solutions, including:

  1. refactoring my code to use SqlBulkCopy
  2. increasing Timeout values, as stated in various answers or checking for
    underlying causes (may not be data related)
  3. Connection Timeout (Default 15s) - How long it takes to wait for a connection to be established with the SQL server before terminating - TCP/PORT related - can go through a troubleshooting checklist (very handy MSDN article)
  4. Command Timeout (Default 30s) - How long it takes to wait for the execution of a query - Query execution/network traffic related - also has a troubleshooting process (another very handy MSDN article)
  5. Rebooting of the server(s) - both application & DB Server (if separate) - where code and data haven't changed, environment must have changed - First thing you must do. Typically caused by patches (operating system, .Net Framework or SQL Server patches or updates). Particularly if timeout exception appears as below (even if we do not use Azure):
    • System.Data.Entity.Core.EntityException: An exception has been raised that is likely due to a transient failure. If you are connecting to a SQL Azure database consider using SqlAzureExecutionStrategy. ---> System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.) ---> System.ComponentModel.Win32Exception: The semaphore timeout period has expired
╰ゝ天使的微笑 2024-12-29 14:15:15

我曾经遇到过这个问题,在我的例子中是 SQL 中未提交的事务。在我承诺之后,问题就消失了。

I had this problem once and in my case was an uncommited transaction in SQL. After I commited, the problem went away.

◇流星雨 2024-12-29 14:15:15

@SilverLight..这显然是数据库对象的问题。这可能是查询写得不好,或者缺少索引。但到目前为止,我不会建议您在不调查数据库对象问题的情况下增加超时。

NovinMedia.Data.DbObject.RunProcedure(String storedProcName, IDataParameter[] parameters, Int32& rowsAffected) +209

在这行代码上放置断点以找出过程名称,然后通过查看其执行计划来优化过程。

在您发布有关存储过程的详细信息之前,我无法为您提供更多帮助。

@SilverLight.. This is clearly an issue with a Database object. It can be a badly written query, or missing indexes. But as of now I won't suggest you to increase the timeout without investigating the issue with your Database objects

NovinMedia.Data.DbObject.RunProcedure(String storedProcName, IDataParameter[] parameters, Int32& rowsAffected) +209

Put a breakpoint on this line of code to findout the procedure name and then optimise the procedure by looking at its execution plan.

I cannot help you more till the time you post details about the stored procedure.

贵在坚持 2024-12-29 14:15:15

就我而言,我使用了EntityFrameworkCore
由于我想要处理的输入超出了查询限制,因此我出现了此错误。
我的案例的解决方案是将数据处理拆分,通过这种方法,我能够适应限制。
是的,这需要时间,但至少它处理了所有输入记录。

In my case I used EntityFrameworkCore.
Since the input I wanted to be processed exceeded the query limit this error came to me.
The solution for my case was to split the data processing into chunks and by this approach I was able to fit within the limits.
Yes, it takes time, but at least it processes all of the input records.

不气馁 2024-12-29 14:15:15

尝试

EXEC SP_CONFIGURE 'remote query timeout', 1800
reconfigure
EXEC sp_configure

EXEC SP_CONFIGURE 'show advanced options', 1
reconfigure
EXEC sp_configure

EXEC SP_CONFIGURE 'remote query timeout', 1800
reconfigure
EXEC sp_configure

那么 一下
重建你的索引

try

EXEC SP_CONFIGURE 'remote query timeout', 1800
reconfigure
EXEC sp_configure

EXEC SP_CONFIGURE 'show advanced options', 1
reconfigure
EXEC sp_configure

EXEC SP_CONFIGURE 'remote query timeout', 1800
reconfigure
EXEC sp_configure

then
rebuild your index

迷途知返 2024-12-29 14:15:15

还要确保您没有待处理的交易。 :)

我正在做一些测试并开始安全交易但从未关闭它。我希望错误能更明确,但是哦,好吧!

Also make sure you just don't have a pending transaction. :)

I was doing some tests around and began a transaction to be safe but never closed it. I wish the error would have been more explicit but oh well!

与君绝 2024-12-29 14:15:15

我们在超时已过期/达到最大池Sqlexception方面遇到了困难。作为一种解决方法,为了防止重新启动服务器或服务,我们修改了 SQL Server 中的 MAX SERVER MEMORY 变量(通过 SQL Managment Studio 或 T-SQL):

DECLARE @maxMem INT = 3000 --Max. memory for SQL Server instance in MB
EXEC sp_configure 'show advanced options', 1
RECONFIGURE

这会暂时解决该问题,直到问题再次发生。在我们的例子中,我们怀疑这与应用程序级别的连接泄漏有关。

We've had hard times on Timeout expired/max pool reached Sqlexception. As a workarround and to prevent restarting the server or the service we modify the MAX SERVER MEMORY variable in SQL Server (either through SQL Managment Studio or T-SQL):

DECLARE @maxMem INT = 3000 --Max. memory for SQL Server instance in MB
EXEC sp_configure 'show advanced options', 1
RECONFIGURE

This temporarily fixes the issue until it happens again. In our case we suspect that it has to do with connection leaks at app level.

卖梦商人 2024-12-29 14:15:15

我们最近升级到了 SqlClient (Microsoft.Data.SqlClient) 的 NuGet 版本,其中包含一个错误。此错误是在 1.x 周期的生命周期中引入的,并且已得到修复。该修复将在 2.0.0 版本中提供,但在撰写本文时尚未提供。可以预览。

您可以在此处检查详细信息:
https://github.com/dotnet/SqlClient/issues/262

We recently upgraded to the NuGet version of SqlClient (Microsoft.Data.SqlClient) which contains a bug. This bug was introduced during the lifetime of the 1.x cycle and has already been fixed. The fix will be available in the 2.0.0 release which is not available at the time of this writing. A preview is available.

You can inspect the details here:
https://github.com/dotnet/SqlClient/issues/262

微暖i 2024-12-29 14:15:15

我遇到了这个问题,当我从 ADO.NetDapper 进行我的查询。

I had this problem and it went away when I moved from ADO.Net to Dapper for my queries.

时光倒影 2024-12-29 14:15:15

超时已过期,因为 sql 查询花费的时间比您设置的时间长
在 sqlCommand.CommandTimeout 属性中。

显然你可以增加CommandTimeout来解决这个问题,但是
在此之前,您必须通过添加索引来优化查询。如果你
Sql server Management studio中运行查询,包括实际
执行计划
然后Sql server management studio会建议
你正确的索引。大多数情况下,您将摆脱超时问题
如果您可以优化您的查询。

Timeout expired because the sql query is taking more time than you set
in sqlCommand.CommandTimeout property.

Obviously you can increase CommandTimeout to solve this issue but
before doing that you must optimize your query by adding index. If you
run your query in Sql server management studio including actual
execution plan
then Sql server management studio will suggest
you proper index. Most of the case you will get rid of timeout issue
if you can optimize your query.

久夏青 2024-12-29 14:15:15

此外,您还需要检查逻辑中是否未更新单个记录,因为该位置的更新触发器也会导致超时错误。

因此,解决方案是确保在循环/光标之后执行批量更新,而不是在循环中一次更新一条记录。

Also you need to check if individual record is not getting updated in the logic because with update trigger in the place causes time out error too.

So, the solution is to make sure you perform bulk update after the loop/cursor instead of one record at a time in the loop.

送你一个梦 2024-12-29 14:15:15

正如其他人所说,问题可能与待处理的交易有关。
就我而言,我必须将 DbTransaction 变量作为 ExecuteScalar 方法中的参数发送,以便正确执行该过程。

之前:

ExecuteScalar(command)

之后:

ExecuteScalar(command, transaction)

As others have said, the problem might be related with a pending transaction.
In my case I had to send the DbTransaction variable as a parameter in the ExecuteScalar method for the procedure to be executed properly.

Before:

ExecuteScalar(command)

After:

ExecuteScalar(command, transaction)
旧时光的容颜 2024-12-29 14:15:15

我在同时连接超过 2000 个用户的多线程程序上遇到同样的错误。当我运行超过 5000 行的 SELECT 命令时,出现了问题。该命令被插入命令阻止。通过将 SELECT * 更改为 SELECT Top(n) * 可以修复 n<5000

i got same error on my multithreading program that has over 2000 user connected simultansely. the problem happened when i run an SELECT command with more than 5000 rows. this command blocked by insert command. by changeing SELECT * to SELECT Top(n) * that n<5000 it fixes

小耗子 2024-12-29 14:15:15

您是否可能忘记了 await 一个 async 语句?如果您的任务最终花费的时间比线程中止时花费的时间更长,您会收到类似的消息。

Did you perhaps forget to await an async statement? You would get a similar message if your task ends up taking longer then when your thread was aborted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文