.NET 数据库连接池类 (修改)

// <summary>  
    /// 数据库连接池  
    /// </summary>    
    internal static class ConnectionPool
    {
        //list of the pool objects  
        private static System.Collections.Generic.HashSet<PooledConnection> pooled;


        //clean-up interval  
        private static readonly long GARBAGE_INTERVAL = 30 * 1000; //默认回收  
        private static readonly long FORCE_GARBAGE_INTERVAL = 20 * 60 * 1000; //强制回收,时隔2分钟  
        private static readonly long LIFECYCLE_GARBAGE_INTERVAL = 10 * 60 * 1000; //生存周期,时隔10分钟   


        private static readonly string CONNECTION_STRING = ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString;


        /// <summary>  
        /// 数据库连接池  
        /// </summary>  
        static ConnectionPool()
        {
            pooled = new HashSet<PooledConnection>();
            //自动回收timer  
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Enabled = true;
            timer.Interval = GARBAGE_INTERVAL;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        }


        /// <summary>  
        /// 仅用户debug;查看连接池连接对象  
        /// </summary>  
        /// <returns></returns>  
        public static string Debug()
        {
            lock (pooled)
            {
                StringBuilder sb = new StringBuilder("--------------" + pooled.Count + "------------");
                sb.AppendLine();
                int i = 0;
                foreach (PooledConnection conn in pooled)
                {
                    sb.AppendLine((i++) + "-Connection hashcode:" + conn.GetConnectionHashCode);
                    sb.Append("-using:" + conn.Using);
                    sb.Append("-state:" + conn.ConnectionState);
                }
                return sb.ToString();
            }
        }


        /// <summary>  
        /// 从连接池获取一个连接对象  
        /// </summary>  
        /// <returns>Oracle连接对象</returns>  
        public static SqlConnection BorrowOpenningConnection()
        {
            lock (pooled)
            {
                int count = pooled.Count;
                for (int i = (count - 1); i >= 0; i--)  //集合和数组的下标都是从零开始的  
                {
                    PooledConnection instance = pooled.ElementAt(i);
                    //如果连接池存在空闲对象  
                    if (!instance.Using)
                    {
                        instance.Using = true;
                        instance.LastCheckOut = DateTime.Now;
                        if (instance.Connection.State != System.Data.ConnectionState.Open) instance.Connection.Open();
                        return instance.Connection;
                    }
                }
                //增加一个连接到连接池  
                PooledConnection n = new PooledConnection(new SqlConnection(CONNECTION_STRING), true);
                pooled.Add(n);
                n.Connection.Open();
                return n.Connection;
            }
        }


        /// <summary>  
        /// 把借出的连接放回到连接池.  
        /// </summary>  
        /// <param name="conn">oracle连接对象</param>  
        public static void ReturnConnection(SqlConnection conn)
        {
            lock (pooled)
            {
                foreach (PooledConnection instance in pooled)
                {
                    if (conn.GetHashCode() == instance.GetConnectionHashCode)
                    {
                        instance.Using = false;
                        instance.LastCheckOut = DateTime.Now;
                        return;
                    }
                }
            }
        }


        /// <summary>  
        /// 自动回收事件  
        /// </summary>  
        /// <param name="sender">Timer对象</param>  
        /// <param name="e">ElapsedEventArgs实例</param>  
        private static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime now = DateTime.Now;
            lock (pooled)
            {
                int count = pooled.Count;
                for (int i = (count - 1); i >= 0; i--)
                {
                    PooledConnection instance = pooled.ElementAt(i);
                    //不在使用中,同時到了它的生命期  
                    //在使用中,最後一次签出时间到現在大于强制回收时间  
                    //不在使用中,不使用的停留时间大于回收时间  
                    if ((!instance.Using && now > instance.Created.AddMilliseconds(LIFECYCLE_GARBAGE_INTERVAL)) || now > instance.LastCheckOut.AddMilliseconds(instance.Using ? FORCE_GARBAGE_INTERVAL : GARBAGE_INTERVAL))
                    {
                        pooled.Remove(instance);
                        if (instance.Connection.State == System.Data.ConnectionState.Open) instance.Connection.Close();
                        instance.Connection.Dispose();
                        SqlConnection.ClearPool(instance.Connection);
                        instance = null;
                    }
                }
            }
        }
        /// <summary>  
        /// 连接池对象  
        /// </summary>  
        class PooledConnection
        {
            DateTime _created = DateTime.Now;
            /// <summary>  
            /// 创建时间  
            /// </summary>  
            public DateTime Created { get { return _created; } }


            DateTime _lastCheckOut = DateTime.Now;
            /// <summary>  
            /// 最后 借出 时间  
            /// </summary>  
            public DateTime LastCheckOut
            {
                get { return _lastCheckOut; }
                set { _lastCheckOut = value; }
            }


            SqlConnection _connection;
            /// <summary>  
            /// 连接对象  
            /// </summary>  
            public SqlConnection Connection
            {
                get
                {
                    return _connection;
                }
            }


            /// <summary>  
            /// 连接状态  
            /// </summary>  
            public System.Data.ConnectionState ConnectionState
            {
                get { return _connection.State; }
            }
            int _connectionHashCode;
            /// <summary>  
            /// 连接对象的hashcode,用于返回借出对象的時候使用  
            /// </summary>  
            public int GetConnectionHashCode
            {
                get { return _connectionHashCode; }
            }


            bool _useng = false;
            /// <summary>  
            /// 是否在使用中  
            /// </summary>  
            public bool Using { get { return _useng; } set { _useng = value; } }


            /// <summary>  
            /// 构造函数  
            /// </summary>  
            /// <param name="connection">连接对象</param>  
            /// <param name="useng">是否在使用中</param>  
            public PooledConnection(SqlConnection connection, bool useng)
            {
                this._connection = connection;
                this._useng = useng;
                this._connectionHashCode = connection.GetHashCode();
            }
        }
    }  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值