SqlConnection.ConnectionTimeout Property

Definition

Gets the time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error.

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

Property Value

The time (in seconds) to wait for a connection to open. The default value is 15 seconds.

Implements

Attributes

Exceptions

The value set is less than 0.

Examples

The following example creates a SqlConnection and sets the Connection Timeout to 30 seconds in the connection string. The code opens the connection and displays the ConnectionTimeout property in the console window.

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

Remarks

You can set the amount of time a connection waits to time out by using the Connect Timeout or Connection Timeout keywords in the connection string. A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.

Applies to

See also