I'm using the following code to test if SQL Server is running, and I'm facing a strange behavior, the result is true only if I set a breakpoint under that statement, otherwise it will return false. My timeout value is set to 120.
public static bool IsServerRunning()
{
string[] serverDetails= serverName.Split(',');
string fullServerName = serverDetails[0];
string[] stringSeparators = new string[] { "\\" };
string[] fullServerNameDetails = fullServerName.Split(stringSeparators, StringSplitOptions.None);
string serverIpAdress = fullServerNameDetails[0];
int serverPort = int.Parse(serverDetails[1]);
int timeout = GetRemoteServerTimeout();
var result = false;
try
{
using ( var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, Sockets.ProtocolType.Tcp) )
{
IAsyncResult asyncResult = socket.BeginConnect(serverIpAdress, serverPort, null, null);
result = asyncResult.AsyncWaitHandle.WaitOne(timeout, true);
socket.Close();
}
return result;
}
catch ( Exception myException )
{
return false;
}
}
UPDATE:
I've found a working solution, however I'm not sure if it the most safe/reliable way to implement it.
private static bool IsServerRunning()
{
try
{
using (var sqlConnection = new SqlConnection(GetConnectionString()))
{
sqlConnection.Open();
return true;
}
}
catch (Exception ex)
{
log.Error("Error message for connection failed " + ex.Message);
return false;
}