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 执行连接,因为尝试连接会无限期等待。

适用于

另请参阅