共用方式為


SqlConnection.ConnectionTimeout 屬性

定義

取得在終止嘗試並產生錯誤前嘗試建立連接的等待時間 (以秒為單位)。

public:
 virtual property int ConnectionTimeout { int get(); };
public:
 property int ConnectionTimeout { int get(); };
public override int ConnectionTimeout { get; }
[System.Data.DataSysDescription("SqlConnection_ConnectionTimeout")]
public int ConnectionTimeout { get; }
member this.ConnectionTimeout : int
[<System.Data.DataSysDescription("SqlConnection_ConnectionTimeout")>]
member this.ConnectionTimeout : int
Public Overrides ReadOnly Property ConnectionTimeout As Integer
Public ReadOnly Property ConnectionTimeout As Integer

屬性值

等待連接開啟的時間 (以秒為單位)。 預設值為 15 秒。

實作

屬性

例外狀況

設定的值小於 0。

範例

下列範例會在 SqlConnection 連接字串 中建立 ,並將 設定Connection Timeout為 30 秒。 程式代碼會開啟連接, ConnectionTimeout 並在主控台視窗中顯示 屬性。

private static void OpenSqlConnection()
{
    string connectionString = GetConnectionString();
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        Console.WriteLine("State: {0}", connection.State);
        Console.WriteLine("ConnectionTimeout: {0}",
            connection.ConnectionTimeout);
    }
}

static private string GetConnectionString()
{
    // To avoid storing the connection string in your code,
    // you can retrieve it from a configuration file, using the
    // System.Configuration.ConfigurationSettings.AppSettings property
    return "Data Source=(local);Initial Catalog=AdventureWorks;"
        + "Integrated Security=SSPI;Connection Timeout=30";
}
Private Sub OpenSqlConnection()
    Dim connectionString As String = GetConnectionString()
    Using connection As New SqlConnection(connectionString)
        connection.Open()

        Console.WriteLine("State: {0}", connection.State)
        Console.WriteLine("ConnectionTimeout: {0}", connection.ConnectionTimeout)
    End Using
End Sub

Private Function GetConnectionString() As String
    ' To avoid storing the connection string in your code,  
    ' you can retrieve it from a configuration file, using the
    ' System.Configuration.ConfigurationSettings.AppSettings property
    Return "Data Source=(local);Database=AdventureWorks;" _
      & "Integrated Security=SSPI;Connection Timeout=30;"
End Function

備註

您可以使用 連接字串 中的 或 Connection Timeout 關鍵詞,設定連線等候Connect Timeout逾時的時間量。 值為 0 表示沒有限制,因此應該避免在 ConnectionString 中,因為嘗試連接會無限期等候。

適用於

另請參閱