小编典典

是否需要手动关闭并处置SqlDataReader?

c#

我在这里处理遗留代码,并且有许多实例SqlDataReader从未关闭或处置过。连接已关闭,但是我不确定是否需要手动管理阅读器。

这会导致性能下降吗?


阅读 353

收藏
2020-05-19

共1个答案

小编典典

尽量避免使用这样的读者:

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语句中:

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语句将确保正确处置对象和释放资源。

如果您忘记了,则将清理工作留给垃圾收集器,这可能需要一段时间。

2020-05-19