c# - 如何超时 "A network-related or instance-specific error occurred while establishing a connection to SQL Server"错误

标签 c# asp.net sql-server command-timeout

我正在使用 sql server,有时我的数据库因维护而停机。我有错误处理代码,因此用户不会看到错误页面,而是会看到友好的错误消息。我的问题是:当数据库关闭时,页面加载和显示错误消息需要很长时间。我认为它与超时属性有关,但使用

更改它
command.CommandTimeout = 5;

Connect Timeout=5; in web.config in connectionString 似乎没有帮助,页面加载仍然需要很长时间(大约 40 秒).有没有办法将这个时间减到最少?

抛出并记录的异常是

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)

最佳答案

那好吧。

我会为所有“数据访问层”类创建一个基类。

public class DataBaseLayer ()
{

public DataBaseLayer()
{ /* check for appSetting here and throw a SqlServerMaintenanceModeException exception (custom exception) */}

}


public class EmployeeDataLayer :  DataBaseLayer ()
    {
public EmployeeDataLayer() : base ()
}

在构造函数中,我会检查一个 appSetting...是否为“true”或“false”......并抛出一个 CustomException

public class SqlServerMaintenanceModeException : ApplicationException

{}

将其放入 DataBaseLayer 的构造函数中......然后让其他一切处理它。

这样...只有“数据库驱动”的页面会受到影响。

我不喜欢检查“超时”的一个小原因是......

  1. 有点不可预测。
  2. 有时这是一个正常的异常......就像你的网络上的一个交换机经过一样。你将如何区分?

我非常不喜欢模棱两可的异常。

关于c# - 如何超时 "A network-related or instance-specific error occurred while establishing a connection to SQL Server"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17550900/

相关文章:

c# - 克隆匿名类型?

asp.net - asp 菜单 css 的浏览器兼容性在 google chrome 中不起作用

asp.net - bcrypt/Bcrypt.net 的优势和替代方案

sql-server - 如何将Oracle包转换为SQL Server?

c# - 合并 MDI 窗口的菜单条项

c# - 如何将光标置于C#中Datepicker控件的第一个位置?

c# - 如何在asp :BoundField?中将日期时间更改为本地GMT日期时间

c# - 在 Visual Studio 中添加新数据项时 EF 6.x DbContext 生成器选项的用途

sql - 将 EXECUTE sp_executesql 结果设置为 sql 中的变量

sql-server - 从一列保存多种数据类型为 varchar 的表中进行选择