Dela via


SqlConnection.ConnectionTimeout Property

Definition

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

public:
 virtual property int ConnectionTimeout { int get(); };
public override int ConnectionTimeout { get; }
member this.ConnectionTimeout : int
Public Overrides ReadOnly Property ConnectionTimeout As Integer

Property Value

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

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.

using Microsoft.Data.SqlClient;

class Program
{
    static void Main()
    {
        OpenSqlConnection();
        Console.ReadLine();
    }

    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";
    }
}

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