Question

I know you can set the Connection Timeout parameter on the ConnectionString, however, it sets the minimum timeout time and not the maximum.

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.

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.

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. It doesn't work perfectly but works better. It have to be set on every new DataContext object but it's fine. I set to a value X and it seems to always take X + 5 seconds to throw a Timeout exception.

Was it helpful?

Solution 2

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; 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.

OTHER TIPS

the ConnectionTimeout is the timeout for the connection Open() call. It doesn't apply to commands at all. The CommandTimeout applies to the Execute or ExecuteScalar calls. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top