更改SQL Server连接的连接超时无效

时间:2015-03-04 07:29:20

标签: c# sql-server connection-timeout

我正在尝试使用以下代码设置在C#中与SQL服务器建立连接的超时时间:

var sscsb = new SqlConnectionStringBuilder(sConn);
sscsb.ConnectTimeout = 10;                 

SqlConnection connection = new SqlConnection(sscsb.ConnectionString);

using (connection)
{                       
    connection.Open();
    connection.Close();
    return (true);
}

但在connection.Open()语句抛出错误之前经过了30秒。如何将连接超时设置为较短的值?

3 个答案:

答案 0 :(得分:0)

当我尝试连接到无效的服务器名称时,或者当与有效服务器的网络连接断开时,我遇到了此问题。在这些情况下,超时值被忽略。似乎超时不适用于验证服务器并发送连接请求的尝试。它似乎只适用于找到有效服务器并发出请求后等待连接的时间。

我使用了基于计时器的解决方案,虽然我似乎无法找到它,但这绝对是一种解决方法。 This threading-based solution似乎是要走的路。

答案 1 :(得分:0)

我曾经调查过这个问题并得出了这样的结论: 连接字符串或连接中指定的连接超时意味着:如果sql服务器正在侦听,请等待x秒以使其接受连接请求。如果没有服务器正在侦听端口(例如,sql server未运行),则使用默认套接字连接超时,默认为30秒。 解决方法是使用自定义超时手动打开与sql server的套接字连接,以检查它是否正在运行。

答案 2 :(得分:0)

下面的代码测试连接并能够在连接上运行查询。查询需要引用目标D / B中的小表:

 /// <summary>
    ///  Return true if successful SQL connection 
    /// </summary>
    /// <param name="conn"></param>
    /// <param name="timeout">timeout in msec</param>
    /// <returns></returns>
    public static bool QuickSQLConnectionTest(SqlConnection conn, int timeout)
    {
        // We'll use a Stopwatch here for simplicity. A comparison to a stored DateTime.Now value could also be used
        Stopwatch sw = new Stopwatch();
        bool connectSuccess = false;

        // Try to open the connection, if anything goes wrong, make sure we set connectSuccess = false
        Thread t = new Thread(delegate()
        {
            try
            {
                sw.Start();
                conn.Open();
                SqlCommand cmd = new SqlCommand("Select Count(*) from Configuration", conn);
                cmd.CommandTimeout = timeout/1000; // set command timeout to same as stopwatch period
                cmd.ExecuteScalar();
                connectSuccess = true;
            }
            catch (Exception Ex)
            {
            }
        });


        // Make sure it's marked as a background thread so it'll get cleaned up automatically
        t.IsBackground = true;
        t.Start();

        // Keep trying to join the thread until we either succeed or the timeout value has been exceeded
        while (timeout > sw.ElapsedMilliseconds)
            if (t.Join(1))
                break;

        // If we didn't connect successfully
        if (!connectSuccess)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
相关问题