是否需要手动关闭和处置SqlDataReader的呢?SqlDataReader

2023-09-02 20:43:23 作者:守着你看贫贱落尽ヽ

我与旧code在这里工作,有 SqlDataReader的的许多情况下是不会被关闭或释放。连接被关闭,但是,我不知道这是否是必要的手动管理的读者。

I'm working with legacy code here and there are many instances of SqlDataReader that are never closed or disposed. The connection is closed but, I am not sure if it is necessary to manage the reader manually.

难道这会导致经济放缓的表现呢?

Could this cause a slowdown in performance?

推荐答案

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

Try to avoid using readers like this:

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

Instead, wrap them in using statements:

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语句将确保正确处理资源的目标和释放的。

The using statement will ensure correct disposal of the object and freeing of resources.

如果你忘记了,那么你留下清理的垃圾收集器,这可能需要一段时间。

If you forget then you are leaving the cleaning up to the garbage collector, which could take a while.

 
精彩推荐
图片推荐