0

Possible Duplicate:
How to catch SQLServer timeout exceptions

I have the following code:

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MainDll"].ToString()))
{
    connection.Open();
    using (SqlCommand command = new SqlCommand(sql.ToString(), connection))
    {
        command.CommandType = CommandType.Text;
        command.CommandTimeout = 300;
        returnCode = (string)command.ExecuteScalar();
        //Dispose();
    }
}

How do I know when the timeout has been reached? I want to grab it and do something with the SQL after the timeout.

Community
  • 1
  • 1
cdub
  • 24,555
  • 57
  • 174
  • 303

2 Answers2

1

You can only know the Timeout is reached when a error is thrown

So I would suggest is try to handle the exception and if TimeOut exception is caught thats the time you can do as per your requirement

HatSoft
  • 11,077
  • 3
  • 28
  • 43
0
try {
  //your code
}
catch (SqlException ex) {
  if (ex.Number == -2) { //System.Data.SqlClient.TdsEnums.TIMEOUT_EXPIRED
    //handle timeout
  }
  else {
    throw;
  }
}
finally {
  //cleanup
}

Source: This SO thread.

Community
  • 1
  • 1
Channs
  • 2,091
  • 1
  • 15
  • 20