/// <summary> /// 关闭连接,返回连接池 /// </summary> /// <param name="dbw"></param> public void ReleaseConn(DbConnectionWrapper dbw) { if (dbw == null) { return; } lock (this._lockObject) { if (this._dbUsed.Contains(dbw)) { this._dbUsed.Remove(dbw); //如果连接已经不能用,则释放掉 if (dbw.CanUse()) { this._dbCanUse.Add(dbw); } else { try { dbw.Conn?.Close(); } catch { } } } else { this._dbCanUse.Add(dbw); } } }
private int _checkConnTimeout = 60; //60s /// <summary> /// 使用连接信息构造一个数据库连接管理类 /// </summary> /// <param name="connInfo"></param> /// <param name="initConn">初始连接:5,建议和最小池子数一致</param> /// <param name="timeout">30s</param> public DbConnectionManager(DbConnOption connInfo, int initConn = 5, int timeout = 30) { this._initConn = initConn; this._connInfo = new DbConnOption(connInfo.DbConnectionString, connInfo.DbConnectionType); if (initConn > 0) { DbConnectionWrapper[] arrConn = new DbConnectionWrapper[initConn]; Parallel.For(0, initConn, x => { arrConn[x] = this.CreateNew(); }); this._dbCanUse.AddRange(arrConn.Where(x => x != null)); } //开启线程,定时检查释放多余的连接 Thread th = new Thread(CheckConn) { IsBackground = true, Priority = ThreadPriority.BelowNormal, Name = "检查数据库连接" }; th.Start(this); }