我有一个称为“ 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()会自动关闭连接。但是,看来现在还没有关闭。你能启发我吗?谢谢。
最佳答案
MSDN中的CommandBehavior.CloseConnection
执行该命令时,关联的Connection对象为
当关联的DataReader对象关闭时关闭。
因此,仅当您关闭DataReader时,连接才会关闭。