我正在编写C#代码并使用LINQ和一些存储过程,我小心打开和关闭连接,但我一直收到此错误。
Timeout expired.
The timeout period elapsed prior to obtaining a connection from the pool.
This may have occurred because all pooled connections were in use and max pool size was reached.
我的代码完全正常,除了出现此错误,我该怎么办呢?
感谢任何想法。
public static List<int> GetIslemIdleribySPbyCariId(int cariId)
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer1"].ConnectionString;
SqlConnection sqlConn = new SqlConnection(connString);
sqlConn.Open();
List<int> islemidleri = new List<int>();
islemidleri.Clear();
SqlCommand cmd;
cmd = new SqlCommand("GetIslemIdleri", sqlConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@CARIID", cariId));
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
islemidleri.Add(reader.GetInt32(0));
}
cmd.Parameters.Clear();
}
sqlConn.Close();
return islemidleri;
}
/// <summary>
/// SP kullanarak dovizturlerini döndürür
/// </summary>
/// <returns>string listesi döndürür için döviz türleri var TL, USD vs.</returns>
public static List<string> GetDovizTurleribySP()
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer1"].ConnectionString;
SqlConnection sqlConn = new SqlConnection(connString);
sqlConn.Open();
List<string> dovizTanimlari = new List<string>();
string commandGetDovizTanimlari = "EXEC GetDovizTanimlari";
SqlCommand cmd;
cmd = new SqlCommand(commandGetDovizTanimlari, sqlConn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
dovizTanimlari.Add(reader.GetString(0));
}
}
return dovizTanimlari;
}
答案 0 :(得分:3)
从您的代码中,您没有关闭GetDovizTurleribySP
功能中的连接。我建议您使用using
语句来确保即使发生异常也会关闭连接。
它可能看起来像这样
public static List<string> GetDovizTurleribySP()
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer1"].ConnectionString;
using (SqlConnection sqlConn = new SqlConnection(connString))
{
sqlConn.Open();
List<string> dovizTanimlari = new List<string>();
string commandGetDovizTanimlari = "EXEC GetDovizTanimlari";
SqlCommand cmd;
cmd = new SqlCommand(commandGetDovizTanimlari, sqlConn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
dovizTanimlari.Add(reader.GetString(0));
}
}
return dovizTanimlari;
}
}
答案 1 :(得分:1)
在看到你的代码之后我想指出的两件事情,将sqlCommand,DataReader和sqlConnection包装在using语句中(是的嵌套使用语句),当你创建List时,你不必再调用clear()列表应该已经初始化为emtpy(至少我认为是在c#中)。
答案 2 :(得分:0)
测试和测试:
Close();
Dispose();
SqlConnection.ClearPool(connection);
SqlConnection.ClearAllPools();
使用表达式,最后我发现每个OpenConnection的“Open Pools”问题没有重用“Pool”维护(AWAITING COMMAND)导致ASP.NET客户端应用程序饱和(唯一的方法是重启要发布的IIS),我意识到这是对.config中的连接字符串的调用:
*System.Configuration.ConfigurationManager.ConnectionStrings ["ConnectionSQL"] ConnectionString.;*
显然他调用外部程序集,导致连接字符串或散列“差异”。
<强>解决方案:强>
我把议会加起来了:
System.Configuration"** and replacement implicitly invoking: ConfigurationManager.ConnectionStrings ["ConnectionSQL"] ConnectionString;
这解决了问题,每个“Open()”都没有执行“Pools”。