zoukankan      html  css  js  c++  java
  • 数据库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
  • 相关阅读:
    Linux -- nginx
    Linux--虚拟环境
    Linux用户权限指令, 定时任务等指令
    Linux的基础命令, django的安装与使用
    .net与Java的WebService互调
    C#中的动态特性
    LINQ之路(3):LINQ扩展
    LINQ之路(2):LINQ to SQL本质
    LINQ之路(1):LINQ基础
    LINQ之路系列文章导读
  • 原文地址:https://www.cnblogs.com/musexiaoluo/p/7373852.html
Copyright © 2011-2022 走看看