A number of discussions like this are treating how to check if a SQL connection is open, using the ConnectionState enum. Recently I have experienced that a ConnectionState.Open
may not always tell the truth in .NET 2.0.
If the connection is broken from outside while my C# application is running, the connection state is not updated. Since it still claims that the connection is open, I can not use the following assurance method:
if(Something_Connection.State != ConnectionState.Open)
{
Something_Connection.Close();
Something_Connection.Open();
}
The issue may be reproduced using the following test. Assuming that you initially have an open connection m_dbConnection
and a working command line method CommandLineUtils.Run(...)
:
[Test]
public void ConnectionStateDoesNotLie()
{
// Close SQL service:
Console.WriteLine(CommandLineUtils.Run("net", "stop \"SQL Server (MSSQLSERVER)\"", 10));
System.Threading.Thread.Sleep(500);
// Check state:
bool stateIsCorrect = m_dbConnection.ConnectionState != ConnectionState.Open;
// Finished testing, restart the SQL service:
Console.WriteLine(CommandLineUtils.Run("net", "start \"SQL Server (MSSQLSERVER)\"", 30));
Assert.IsTrue(stateIsCorrect, "Connection state of closed connetion claims to be open.");
}
My question is if there is a better method to check if a connection has been broken? Prior to running a query.
Of cause I could run every query in a try-catch
and then try to reopen the connection if an exception is thrown. But this seems like a clumsy solution. I also want to avoid running any dummy update to test the connection prior to every query in my program.
(Why would I want to stop my SQL service during runtime? I would not, but people using my program may sometimes leave it open for 5 hours and then come back expecting it to work. Sometimes their connection may have failed during this period)