我有一个名为“db”的泛型类,它直接与数据库对话。并有一个名为“ExecuteDataReader”的方法如下:
public SqlDataReader ExecuteDataReader(SqlCommand cmd)
{
try
{
OpenConnection();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return dr;
}
catch (Exception ex)
{
Utils.Debug(string.Format("Err in {0}.{1} : {2}\nSQL : {3}", this.GetType(), "ExecuteDataReader", ex.Message, cmd.CommandText));
return null;
}
}
然后,我执行资源密集型查询,循环遍历10000个父记录和20000个子记录以在数据库中更新。然后我收到以下错误:
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.
要解决这些问题,我必须在执行后显式调用dr.Close()。
static void ProcessAssessmentCriteria(string UnitReference)
{
SqlCommand cmd = new SqlCommand("TRACKING.DBTool_GetUniqueAssessmentCriteriaByUnitReference");
cmd.Parameters.Add("@UnitReference", SqlDbType.VarChar, 20).Value = UnitReference;
SqlDataReader dr = db.ExecuteDataReader(cmd);
if (dr.HasRows)
{
while (dr.Read())
{
ProcessDetailAssessmentCriteria(UnitReference, dr["AssessmentRefNumber"].ToString());
Console.WriteLine("---------------");
}
}
dr.Close();
}
据我所知,CommandBehaviour.CloseConnection()会自动关闭连接。但它似乎现在没有关闭。你能开导我吗?感谢。
答案 0 :(得分:3)
来自MSDN
的CommandBehavior.CloseConnection执行命令时,关联的Connection对象是 关闭关联的DataReader对象时关闭 。
因此,只有在关闭DataReader时,连接才会关闭。