Reputation: 1629
I want to test the database can be connected in fast seconds,for example i want to test it in 3 seconds. I wrote these codes.
bool IsCanConnectioned = false;
string connStr = connectionString + ";Connection Timeout=3000";
SqlConnection sqlConnection = new SqlConnection(connStr);
try
{
sqlConnection.Open();
IsCanConnectioned = true;
}
catch
{
IsCanConnectioned = false;
}
finally
{
sqlConnection.Close();
sqlConnection.Dispose();
}
return IsCanConnectioned;
I broken my network to database for this test, but it's no working to set the connection timeout 3000 or 3. It will throw exception after a long time about more than 15 seconds. (I guess it's because the network timeout) I want to test it in 3 seconds. so is there a good way to do this.
may be It could start a new thread to connect the database,and I wait for the thread 3 seconds,when it's no response or return false,I said the database couldn't be connected,but is there a better way?
Upvotes: 4
Views: 2385
Reputation: 2814
You say you broke the network for this test but ConnectionTimeout applies when you can reach the server on which SqlServer is installed. Otherwise TCP timeout get involved, which by default is 15sec.
If you want to timeout even if the network is down you should setup a tcp connection and try to connect. See this answer on how to do it.
Upvotes: 1
Reputation: 1346
I think you should check sqlConnection.State, which can have any value from state enum.
Also To set the time out For TCP Time out have a look at How to make SqlConnection timeout more quickly
Upvotes: 0