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.

6
  • It should throw an error when it reaches the command timeout. Commented Jul 30, 2012 at 18:36
  • new SqlConnection(ConfigurationManager.ConnectionStrings["MainDll"].ToString())) probably should be new SqlConnection(ConfigurationManager.ConnectionStrings["MainDll"].ConnectionString) Commented Jul 30, 2012 at 18:39
  • @Raphael, this seems like a good link and I'll use this one Commented Jul 30, 2012 at 18:46
  • how do I catch an error with using? Commented Jul 30, 2012 at 18:46
  • 1
    @chris : wether inside the using, or "around" the using. Both are possible. stackoverflow.com/questions/4590490/… Commented Jul 30, 2012 at 18:57

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.