I am trying to change the timeout for a SqlCommand query, in a method that tests my connection for a given connection string. The code is similar to this:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT ...", connection);
cmd.CommandTimeout = 10;
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
...
connection.Close();
}
I would like to have a short timeout here, since I just want to test if this connection string is okay.
But, no matter what number I set on CommandTimeout (I tried 0, 1, 2, 4, 10, 30, 60, 120), my real time obtained for a dummy connection string is always about the same (total running time of about 15 seconds).
So, seems to me that the value I set on CommandTimeout is being ignored for some reason.
Any ideas why?
I think you’re confusing what exactlySqlCommand.CommandTimeoutis for. As per this MSDN reference:In your case, you are executing a DataReader and stepping through your query (whatever it may be). It is taking minimal time for each
Read()which is why you wouldn’t be hitting your timeout.Edit:
If you are using a wrong connection string, your
Timeoutwill not be the Command timeout, but it’ll be the Connection time. This defaults to 15 seconds. That is the timeout that is effective in your situation.You’re going to timeout on the method call
SqlConnection.Open(), notSqlCommand.ExecuteReader(). Therefore theConnectionTimeoutproperty is going to be the effective timeout value.SqlConnection.ConnectionTimeout Property MSDN Reference