数据库Connection.OPEN()异常情况下 耗时很久才回应

一、问题:数据库Connection.OPEN()异常情况下 耗时很久才回应

二、原因:Connection.OPEN() 地址等错误时候 会造成耗时过久才会应的情况。此情况和t数据库连接配置中的Timeout  参数配置无关

三、解决方法:

     利用线程操作看看若指定时间内没反应则视为 配置错误,demo如下。

/// <summary>
    /// 通过监听来查看目标地址是否存在
    /// </summary>
    public static class DataBaseConnectHelper
    {
        public static bool QuickOpen(DbConnection 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();
                    connectSuccess = true;
                }
                catch
                {
                }
            });

            // 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, throw an exception
           /* if (!connectSuccess)
                throw new Exception("Timed out while trying to connect.");*/
                return connectSuccess;
        }
    }
View Code
原文地址:https://www.cnblogs.com/musexiaoluo/p/7373852.html