超时已过。操作完成之前超时时间已过,或者服务器未响应。该声明已终止
我的网站有很多用户(每天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 应用程序)+4052053
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
我有两种获取在线用户的方法:
- 使用
Application["OnlineUsers"] = 0;
- 另一个使用数据库
因此,对于方法#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:
- using
Application["OnlineUsers"] = 0;
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(26)
看起来您的查询花费的时间比应有的时间长。
从堆栈跟踪和代码中,您应该能够准确确定那是什么查询。
这种类型的超时可能有三个原因:
死锁可能很难修复,但很容易确定是否是这种情况。使用 Sql Server Management Studio 连接到您的数据库。在左侧窗格中,右键单击服务器节点并选择“活动监视器”。查看正在运行的进程。
通常大多数会处于空闲或运行状态。当问题发生时,您可以通过进程状态识别任何被阻止的进程。如果您右键单击该进程并选择详细信息,它将显示该进程执行的最后一个查询。
第二个问题将导致数据库使用次优的查询计划。可以通过清除统计信息来解决:
如果这不起作用,您也可以尝试
在服务器负载较重时不应该这样做,因为它会暂时导致性能下降,因为所有存储过程和查询在第一次时都会重新编译被执行。
但是,由于您指出问题有时会发生,并且堆栈跟踪表明您的应用程序正在启动,因此我认为您正在运行一个仅偶尔运行的查询。强制 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;
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:
If that doesn't work you could also try
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.
在运行存储过程的代码中,应该有类似这样的内容:
添加这样一行代码:
这将等待操作完成所需的时间。
In your code where you run the stored procedure you should have something like this:
Add such a line of code:
This will wait as much time as needed for the operation to complete.
您可以设置 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.
我遇到了同样的问题,并通过在 web.config 文件中添加“连接时间”值来解决。找到连接字符串并添加 Connection Timeout=3600"
这是示例
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
也许这对某人有用。
我遇到了同样的问题,在我的例子中,原因是 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.
您必须设置 CommandTimeout 属性。您可以在 DbContext 子类中设置 CommandTimeout 属性。
You have to set CommandTimeout attribute. You can set the CommandTimeout attribute in DbContext child class.
虽然所有早期的回复都解决了这个问题,但它们并未涵盖所有情况。
Microsoft 已承认该问题,并于 2011 年针对受支持的操作系统修复了该问题,因此,如果您得到如下堆栈跟踪:
您可能需要更新您的 .NET 程序集。
有关详细信息,请参阅知识库文章 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:
you may need to update your .NET assemblies.
See KB 2605597 for details
https://support.microsoft.com/kb/2605597
如果您使用带有
Startup.cs
约定的 ASP.NET Core,您可以像这样访问和设置查询命令超时选项:If you are using ASP.NET Core with the
Startup.cs
convention, you can access and set the query command timeout option like this:我遇到了同样的问题,花了大约三天的时间。我注意到,由于我们的记录数量不多,我们的高级开发人员在数据库中保留了 2 张图像和指纹。当我尝试获取这个十六进制值时,它需要很长时间,我计算出执行程序的平均时间约为 38 秒。默认命令超时为 30 秒,因此低于运行存储过程所需的平均时间。我将命令超时设置如下
,它工作正常,但有时如果您的查询花费超过 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
and its working fine but sometimes if your query takes more than 50 seconds it will prompt same error.
我最近遇到了这个错误,经过一些简短的调查,发现原因是我们保存数据库的磁盘空间不足(小于 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.
默认超时为 15 秒,更改为 0 表示无限制,任何其他数字都是秒数。
代码中
在 Web.Config 的 ,“Command Timeout=0;”不要超时,或者低于1小时(3600秒)
Default timeout is 15 seconds, to change that, 0 is unlimited, any other number is the number of seconds.
In Code
In Your Web.Config, "Command Timeout=0;" do not time out, or as below 1 hour (3600 seconds)
我在 sp_foo 中遇到大量计算问题,需要很长时间,所以我修复了
用这个小代码
I have issue with large calculation in sp_foo that take large time so i fixed
with this little bit code
TLDR:
我经常因为各种原因遇到此错误,并有各种解决方案,包括:
根本原因(可能与数据无关)
TLDR:
I have often encountered this error for various reasons and have had various solutions, including:
underlying causes (may not be data related)
我曾经遇到过这个问题,在我的例子中是 SQL 中未提交的事务。在我承诺之后,问题就消失了。
I had this problem once and in my case was an uncommited transaction in SQL. After I commited, the problem went away.
@SilverLight..这显然是数据库对象的问题。这可能是查询写得不好,或者缺少索引。但到目前为止,我不会建议您在不调查数据库对象问题的情况下增加超时。
在这行代码上放置断点以找出过程名称,然后通过查看其执行计划来优化过程。
在您发布有关存储过程的详细信息之前,我无法为您提供更多帮助。
@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
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.
就我而言,我使用了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.
尝试
那么 一下
重建你的索引
try
then
rebuild your index
还要确保您没有待处理的交易。 :)
我正在做一些测试并开始安全交易但从未关闭它。我希望错误能更明确,但是哦,好吧!
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!
我们在
超时已过期/达到最大池
Sqlexception
方面遇到了困难。作为一种解决方法,为了防止重新启动服务器或服务,我们修改了 SQL Server 中的 MAX SERVER MEMORY 变量(通过 SQL Managment Studio 或 T-SQL):这会暂时解决该问题,直到问题再次发生。在我们的例子中,我们怀疑这与应用程序级别的连接泄漏有关。
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 theMAX SERVER MEMORY
variable in SQL Server (either through SQL Managment Studio or T-SQL):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.
我们最近升级到了
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
我遇到了这个问题,当我从 ADO.Net 到 Dapper 进行我的查询。
I had this problem and it went away when I moved from ADO.Net to Dapper for my queries.
此外,您还需要检查逻辑中是否未更新单个记录,因为该位置的更新触发器也会导致超时错误。
因此,解决方案是确保在循环/光标之后执行批量更新,而不是在循环中一次更新一条记录。
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.
正如其他人所说,问题可能与待处理的交易有关。
就我而言,我必须将 DbTransaction 变量作为 ExecuteScalar 方法中的参数发送,以便正确执行该过程。
之前:
之后:
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:
After:
我在同时连接超过 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
您是否可能忘记了
await
一个async
语句?如果您的任务
最终花费的时间比线程中止时花费的时间更长,您会收到类似的消息。Did you perhaps forget to
await
anasync
statement? You would get a similar message if yourtask
ends up taking longer then when your thread was aborted.