0

可能重复:
如何捕获 SQLServer 超时异常

我有以下代码:

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();
    }
}

我如何知道何时达到超时?我想在超时后抓住它并用 SQL 做一些事情。

4

2 回答 2

1

只有在抛出错误时才能知道达到了 Timeout

所以我建议尝试处理异常,如果捕获到 TimeOut 异常,那是你可以根据你的要求做的时间

于 2012-07-30T18:39:33.967 回答
0
try {
  //your code
}
catch (SqlException ex) {
  if (ex.Number == -2) { //System.Data.SqlClient.TdsEnums.TIMEOUT_EXPIRED
    //handle timeout
  }
  else {
    throw;
  }
}
finally {
  //cleanup
}

资料来源:这个SO 线程。

于 2012-07-30T18:51:03.267 回答