/// <summary> /// 清理所有存在的连接 /// 然后重新创建 /// </summary> public void Clear() { poolState = POOL_SUSPENDED; PoolEntry poolEntry = null; //清理资源 while (true) { if (connectionBag.TryPop(out poolEntry)) { CloseConnection(poolEntry.Close()); } else if (connectionBag.IsEmpty) { break; } else { continue; } } size = 0; // keepingExecutor.Clear(); //清除 poolState = POOL_NORMAL; resetEvent.Set(); //恢复等待; }
/// <summary> /// 关闭池,不能再使用 /// </summary> public void ShutDown() { lock (lock_obj) { try { poolState = POOL_SHUTDOWN; PoolEntry poolEntry = null; //清理资源 while (true) { if (connectionBag.TryPop(out poolEntry)) { CloseConnection(poolEntry.Close()); } else if (connectionBag.IsEmpty) { break; } else { continue; } } size = 0; keepingExecutor.Stop();//清除所有资源 LogPoolState("Before shutdown "); } finally { LogPoolState("After shutdown "); } } }
/// <summary> /// 释放使用 /// </summary> /// <param name="poolEntry"></param> internal void Recycle(PoolEntry poolEntry) { if (poolEntry.State == IConcurrentBagEntry.STATE_REMOVED) { //已经标记移除的不能再加入,集合也不允许 CloseConnection(poolEntry.Close()); return; } if (!connectionBag.Push(poolEntry)) { CloseConnection(poolEntry.Close()); } else { //监视空闲 keepingExecutor.ScheduleIdleTimeout(poolEntry); } }
/// <summary> /// 超时获取 /// </summary> /// <param name="hardTimeout">毫秒</param> /// <returns></returns> public IDbConnection GetConnection(long hardTimeout) { if (poolState == POOL_SHUTDOWN) { return(null); } if (poolState == POOL_SUSPENDED) { //挂起操作 resetEvent.WaitOne(); } long startTime = DateTime.Now.Ticks; try { long timeout = hardTimeout; do { PoolEntry poolEntry = null; if (connectionBag.TryPop(out poolEntry)) { try { if (poolEntry.State == IConcurrentBagEntry.STATE_REMOVED) { //已经要移除的 CloseConnection(poolEntry.Close()); continue;//继续获取 } keepingExecutor.ScheduleUse(poolEntry); } catch (Exception ex) { throw new Exception("获取失败:" + ex.Message); } //每次产生代理连接,代理连接在外面会关闭,返回连接池的对象 return(poolEntry.CreateProxyConnection(DateTime.Now.Ticks)); } else { CheckPool();//监测连接 if (size < config.MaximumPoolSize) { //创建新的,不再进入集合 poolEntry = CreatePoolEntry(); if (poolEntry != null) { poolEntry.CompareAndSetState(IConcurrentBagEntry.STATE_NOT_IN_USE, IConcurrentBagEntry.STATE_IN_USE); keepingExecutor.ScheduleUse(poolEntry); return(poolEntry.CreateProxyConnection(DateTime.Now.Ticks)); } else { continue; } } } //计算获取的时间,转化成ms timeout = timeout - (DateTime.Now.Ticks - startTime) / tickms; } while (timeout > 0L); } catch (Exception e) { throw new SQLException(poolName + " - Interrupted during connection acquisition", e); } finally { } return(null); }