public class SqlConnectionContainer
    {
       

 private static Dictionary<int, SqlConnection> connList = new Dictionary<int, SqlConnection>();
        private static int currentNumber = 0;
        private static readonly int maxNumber;  // 连接池链接数量的最大数

        private static string connstring="";//配置文件初始化

        private static object lockObject = new object();

        static SqlConnectionContainer()
        {
            maxNumber = 20; //可以从配置文件中读取
        }

        public static DbConnection GetConnection()
        {

            lock (lockObject)  //防止 并发操作
            {

                for (int i = 0; i < connList.Count; i++)
                {
                    if (connList[i+1].State == ConnectionState.Closed)
                    {
                        return connList[i+1];
                    }
                }
                //没找到 可用的链接

                if (currentNumber > maxNumber)  //判断连接池是否满了
                {
                    throw new Exception("超过了最大连接池数量");
                }

                SqlConnection conn = new SqlConnection(connstring);
                connList.Add(connList.Count+1, conn);

                currentNumber++;
                return conn;
            }
        }
    }

 //泛型连接池类

 public class SqlConnectionContainer2<T> where T : DbConnection
    {
        private static Dictionary<int, T> connList = new Dictionary<int, T>();
        private static int currentNumber = 0;
        private static readonly int maxNumber;  // 连接池链接数量的最大数


        private static string connstring=ConfigurationManager.ConnectionStrings["Test"].ToString();

        private static object lockObject = new object();

        static  SqlConnectionContainer2()
        {
            maxNumber = 30;
        }

        public static T GetConnection()
        {

            lock (lockObject)  //防止 并发操作
            {

                for (int i = 0; i < connList.Count; i++)
                {
                    if (connList[i+1].State == ConnectionState.Closed)
                    {
                        return connList[i+1];
                    }
                }
                //没找到 可用的链接

                if (currentNumber > maxNumber)  //判断连接池是否满了
                {
                    throw new Exception("超过了最大连接池数量");
                }
                T xx =(T) Activator.CreateInstance(typeof(T));
                connList.Add(connList.Count + 1, xx);

                currentNumber++;
                return xx;
            }
        }
    }

posted on 2009-06-03 10:34  悲哀ing  阅读(1029)  评论(3编辑  收藏  举报