共用方式為


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 A 開啟時連接字串中包含「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);
         }
      }
   }
}

適用於

另請參閱