個人覺得寫得還不錯,收藏.原文地址:http://www.cnblogs.com/woaixueyu/archive/2009/06/03/1495140.html
Code
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();
public static SqlConnectionContainer(int max)
{
maxNumber = max;
}
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;
}
}
}