繁体   English   中英

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

[英]Changing Connection Timeout for SQL Server connection has no effect

我正在尝试使用以下代码设置与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秒。 如何将连接超时设置为较短的值?

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

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

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

下面的代码测试连接并能够在连接上运行查询。 查询需要引用目标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;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM