I use SqlConnection in C# and I open the connection with sqlconnection.Open()
to a VM were MSSQL runs on it. If the credentials are correct, the connection is available below a second. But if e.g. the DB is not available, it causes a long Timeout about 45 seconds.
That is why I added to the Connection string Connection Timeout={Timeout}
, this gets assigned because sqlConnection.ConnectionTimeout
is equal the Timeout I set.
I set the Timeout to 5 sec and tried to connect to a not existing Database. Unfortunately, the Timeout was longer than I expected.
20/06/2018 08:04:39: Open Connection
20/06/2018 08:05:11: Connection failed
My goal would be to break up the connection after ca. 10 sec.
TL;DR; Can I affect the Timeout? And if this is not possible, why is the Timeout about 32 sec. even though I set the Timeout to 5 sec.
EDIT:
connectionstring = $@"Server={Ip};Database={DbName};User Id={Username};Password={Password};Connection Timeout={Timeout}";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
try {
Debug.WriteLine(DateTime.Now + "Open Connection");
sqlConnection.Open();
}
catch
{
Debug.WriteLine(DateTime.Now + "Connection failed");
}
}
EDIT 2:
I add ConnectRetryCount=0;ConnectRetryInterval=1;
to the Connection string, it didn't made any change.
https://stackoverflow.com/a/50944424/5507322 - Fair point, but it does not work in all scenarios.
An explanation of this above, why it is not reliable and the solution to my problem: http://improve.dk/controlling-sqlconnection-timeouts/