SqlCommand.CommandTimeout 屬性

定義

取得或設定結束執行命令的嘗試並產生錯誤之前的等待時間 (以秒為單位)。

public:
 virtual property int CommandTimeout { int get(); void set(int value); };
public:
 property int CommandTimeout { int get(); void set(int value); };
public override int CommandTimeout { get; set; }
[System.Data.DataSysDescription("DbCommand_CommandTimeout")]
public int CommandTimeout { get; set; }
member this.CommandTimeout : int with get, set
[<System.Data.DataSysDescription("DbCommand_CommandTimeout")>]
member this.CommandTimeout : int with get, set
Public Overrides Property CommandTimeout As Integer
Public Property CommandTimeout As Integer

屬性值

等待命令執行的時間 (以秒為單位)。 預設值為 30 秒。

實作

屬性

備註

值為 0 表示嘗試執行命令 (無限期等候) 。

注意

CommandTimeout 版 APM (異步程式設計模型會忽略屬性,) 異步方法呼叫,例如 BeginExecuteReader。 較新的 TAP (工作異步程式設計) 方法將會接受,例如 ExecuteReaderAsync

CommandTimeout當命令對內容連線執行時沒有任何作用,SqlConnection (連接字串) 中以 「context connection=true」 開啟的 。

注意

此屬性是叫用方法期間所讀取之所有網路封包的累計逾時 (,) 在命令執行或處理結果期間讀取的所有網路讀取。 傳回第一個數據列之後,仍可能會發生逾時,而且不包含使用者處理時間,只有網路讀取時間。

例如,若有 30 秒逾時,如果需要 Read 兩個網路封包,則會有 30 秒的時間可讀取這兩個網路封包。 如果您再次呼叫 Read ,則會有另 30 秒的時間讀取它所需的任何數據。

using System;
using System.Data.SqlClient;
///
public class A {
   ///
   public static void Main() {
      string connectionString = "";
      // Wait for 5 second delay in the command
      string queryString = "waitfor delay '00:00:05'";
      using (SqlConnection connection = new SqlConnection(connectionString)) {
         connection.Open();
         SqlCommand command = new SqlCommand(queryString, connection);
         // Setting command timeout to 1 second
         command.CommandTimeout = 1;
         try {
            command.ExecuteNonQuery();
         }
         catch (SqlException e) {
            Console.WriteLine("Got expected SqlException due to command timeout ");
            Console.WriteLine(e);
         }
      }
   }
}

適用於

另請參閱