天天看點

用C#建立通用對象池[3]

雖然.NET對資料庫連接配接已經提供了連接配接池,但是,經測試,使用上述通用對象池實作的資料庫連接配接池,效率要比直接使用.NET管理的連接配接池高。因為他減少了Open和Close操作,進而節省了時間。

代碼如下:

    public class DBPool

    {

       private class SqlConnectionObject : IDynamicObject

       {

           private SqlConnection _SqlConn;

           public SqlConnectionObject()

           {

              _SqlConn = null;

           }

           #region IDynamicObject Members

           public void Create(Object param)

           {

              String strConn = (String)param;

              _SqlConn = new SqlConnection(strConn);

              _SqlConn.Open();

           }

           public Object GetInnerObject()

           {

              // TODO:  Add SqlConnectionObject.GetInnerObject implementation

              return _SqlConn;

           }

           public bool IsValidate()

           {

              return ( _SqlConn != null

                  && _SqlConn.GetHashCode() > 0

                  && _SqlConn.State == ConnectionState.Open );

           }

           public void Release()

           {

              // TODO:  Add SqlConnectionObject.Release implementation

              _SqlConn.Close();

           }

           #endregion

       }

       private ObjectPool _Connections;

       public DBPool(string connection, int initcount, int capacity)

       {

           if(connection == null || connection == "" || initcount<0 || capacity < 1)

           {

              throw(new Exception("Invalid parameter!"));

           }

           _Connections = new ObjectPool(typeof(SqlConnectionObject),connection,initcount,capacity);

       }

       public SqlConnection GetConnection()

       {

           return (SqlConnection)_Connections.GetOne();

       }

       public void FreeConnection(SqlConnection sqlConn)

       {

           _Connections.FreeObject(sqlConn);

       }

       public void Release()

       {

           _Connections.Release();

       }

       public int Count

       {

           get{return _Connections.CurrentSize;}

       }

       public int UsingCount

       {

           get{return _Connections.ActiveCount;}

       }

       public int DecreaseSize(int size)

       {

           return _Connections.DecreaseSize(size);

       }

    } // DBPool