简体   繁体   English

在SQL Server中设置最大连接超时的最佳方法

[英]Best way of setting a maximum connection timeout in SQL Server

I know you can set the Connection Timeout parameter on the ConnectionString, however, it sets the minimum timeout time and not the maximum. 我知道您可以在ConnectionString上设置Connection Timeout参数,但是,它设置的是最小超时时间,而不是最大超时时间。

My application works connected to a remote database and it needs to gray out the screen and wait for the connection to come back if it had been lost. 我的应用程序已连接到远程数据库,并且需要将其显示为灰色,如果连接丢失,则等待连接恢复。 I already do this fine, but sometimes when the connection is lost it takes more than 30 seconds to it realize the connection is lost, even with a minimum Connetion Timeout parameter value. 我已经做得很好,但是有时即使丢失了Connetion Timeout参数值,连接断开也要花费30秒钟以上才能意识到连接断开。

I detect the connection is lost because I have a thread doing a polling on the database every 0.5 second, and I wait for it to throw the "A network-related or instance-specific error occurred while establishing a connection to SQL Server" exception. 我检测到连接丢失,因为我有一个线程每0.5秒对数据库进行一次轮询,然后等待它引发“与SQL Server建立连接时发生与网络相关或特定于实例的错误”异常。

I want to know if there is a nice way of setting a maximum timeout or other alternative to it detect faster that the connection is lost. 我想知道是否有一种很好的方法来设置最大超时时间或其他替代方法来更快地检测到连接丢失。

Edit: I didn't know that also existed the CommandTimeout . 编辑:我不知道也存在CommandTimeout It doesn't work perfectly but works better. 它不能完美运行,但是效果更好。 It have to be set on every new DataContext object but it's fine. 必须在每个新的DataContext对象上设置它,但这很好。 I set to a value X and it seems to always take X + 5 seconds to throw a Timeout exception. 我将值设置为X,并且似乎总是需要X + 5秒才能引发Timeout异常。

the ConnectionTimeout is the timeout for the connection Open() call. ConnectionTimeout是连接Open()调用的超时。 It doesn't apply to commands at all. 它根本不适用于命令。 The CommandTimeout applies to the Execute or ExecuteScalar calls. CommandTimeout适用于ExecuteExecuteScalar调用。 It doesn't apply to connections at all. 它根本不适用于连接。

To apply the CommandTimeout to all commands you have to do it every time you create a Command object. 要将CommandTimeout应用于所有命令,则每次创建Command对象时都必须执行此操作。

The best way I found was to create another class to detect when the connection was lost. 我发现最好的方法是创建另一个类来检测何时断开连接。

This class would create 2 threads, one that calls a method to check if the database exists and then set a flag to true; 此类将创建2个线程,一个线程调用一种方法来检查数据库是否存在,然后将标志设置为true;否则,它将创建一个线程。 and another that would check if the flag was true after a certain amount of time. 另一个会在一段时间后检查该标志是否为真。 If it was still false after the certain amount of time, it means that the database connection was lost and the first thread is locked waiting for the timeout. 如果经过一定时间后仍然为假,则意味着数据库连接已丢失,并且第一个线程被锁定以等待超时。 This way I don't need to wait for the timeout to happen to detect it. 这样,我无需等待超时发生就可以检测到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM