我在这里使用的是遗留代码,SqlDataReader
的许多实例从未关闭或处理过.连接已关闭,但我不确定是否需要手动管理读卡器.
这会导致性能下降吗?
我在这里使用的是遗留代码,SqlDataReader
的许多实例从未关闭或处理过.连接已关闭,但我不确定是否需要手动管理读卡器.
这会导致性能下降吗?
尽量避免使用这样的阅读器:
SqlConnection connection = new SqlConnection("connection string");
SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection);
SqlDataReader reader = cmd.ExecuteReader();
connection.Open();
if (reader != null)
{
while (reader.Read())
{
//do something
}
}
reader.Close(); // <- too easy to forget
reader.Dispose(); // <- too easy to forget
connection.Close(); // <- too easy to forget
相反,请使用以下语句将它们包装起来:
using(SqlConnection connection = new SqlConnection("connection string"))
{
connection.Open();
using(SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
//do something
}
}
} // reader closed and disposed up here
} // command disposed here
} //connection closed and disposed here
using语句将确保正确处理对象并释放资源.
如果你忘记了,那么你将把清理工作交给垃圾收集器,这可能需要一段时间.