我的网站有很多用户(每天2万到6万),这是一个移动文件下载网站。我可以远程访问我的服务器(windows server 2008-R2)。我以前收到过“服务器不可用”错误,但我现在看到一个连接超时错误。 我不熟悉这个——为什么会发生这种情况,我该如何解决它?

完整的误差如下:

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


回答后编辑: my Application_Start在全局。Asax是这样的:

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

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

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

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


当前回答

默认超时时间是15秒,要改变它,0是无限的,任何其他数字是秒数。

在代码中

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

在你的网里。配置,“命令超时=0;”不超时,或低于1小时(3600秒)

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

其他回答

我有这个问题,但当我离开ADO后,它就消失了。Net到Dapper为我的查询。

虽然所有早期的答复都涉及这一问题,但并没有涵盖所有情况。

微软已经承认了这个问题,并在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程序集。

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.

详情见KB 2605597

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

正如其他人所说,这个问题可能与悬而未决的事务有关。 在我的例子中,我必须将DbTransaction变量作为ExecuteScalar方法中的参数发送,以便正确地执行过程。

之前:

ExecuteScalar(command)

后:

ExecuteScalar(command, transaction)

在你运行存储过程的代码中,你应该有这样的东西:

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

添加这样一行代码:

c.CommandTimeout = 0;

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

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

这种类型的超时有三个原因;

在某个地方出现了僵局 数据库的统计信息和/或查询计划缓存不正确 查询太复杂,需要调优

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

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

exec sp_updatestats

如果这行不通,你也可以试试

dbcc freeproccache

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

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