2012-07-30 53 views
0

可能重複:
How to catch SQLServer timeout exceptionsSqlCommand.CommandTimeout達到

我有以下代碼:

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做一些事情。

+0

它應該在達到命令超時時發生錯誤。 – Brian 2012-07-30 18:36:04

+0

新的SqlConnection(ConfigurationManager.ConnectionStrings [ 「MAINDLL」]。的ToString())) 大概應該是 新的SqlConnection(ConfigurationManager.ConnectionStrings [ 「MAINDLL」]。的ConnectionString) – Mithrandir 2012-07-30 18:39:33

+0

@Raphael,這似乎是一個很好的鏈接和我會用這個 – cdub 2012-07-30 18:46:23

回答

1

你只能知道超時時,則會引發錯誤

達到所以我建議是嘗試處理異常,如果超時異常被捕獲這就是時間,你可以做按您的要求

0
try { 
    //your code 
} 
catch (SqlException ex) { 
    if (ex.Number == -2) { //System.Data.SqlClient.TdsEnums.TIMEOUT_EXPIRED 
    //handle timeout 
    } 
    else { 
    throw; 
    } 
} 
finally { 
    //cleanup 
} 

來源:This SO線程。