关闭 SQLDataReader - 如何判断它们是否已关闭?

2023-12-29

我发现我遇到了一些网站连接池问题,我正在追踪它们。我知道要寻找的一件事是确保所有 SQLDataReaders 都已关闭,我已经检查并确保它们已关闭。我脑海中浮现的一个问题是关于返回 SQLDataReaders 的方法以及它们如何关闭(或不关闭)。

以下是我的设置方式和一些示例方法:

public static SqlDataReader ExecuteReader(SqlCommand cmd)
{
    SqlConnection c = new SqlConnection(Properties.Settings.Default.DatabaseConn);
    cmd.Connection = c;
    c.Open();
    return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}

然后我有一个使用“ExecuteReader()”的方法

public static SqlDataReader GetData()
{
  SqlCommand Query = new SqlCommand("select * from SomeTable");
  return ExecuteReader(Query);
}

现在假设我有另一个调用“GetData”的方法。我显然简化了事情。

public static SqlDataReader GetMoreData()
{
  return GetData;
}

所以我的问题是,当我像这样调用“GetMoreData”时

SqlDataReader dr = GetMoreData();
//do some stuff with 'dr'
dr.close();

Are all我的 SqlDataReaders 和连接是否正确关闭?

Thanks!


描述

The SqlDataReader实施IDisposable界面。 在每个实现的类上IDisposable你应该打电话Dispose or use using为了释放资源,在这种情况下关闭读取器和底层连接。

I一次性接口定义释放分配资源的方法。

Sample

using(SqlDataReader dr = GetMoreData()) 
{
    try
    {   
       // do your stuff
    }
    catch(Exception ex)
    {
       // handle the exception
    }
} // the reader will get closed here

or

SqlDataReader dr;
try
{   
    dr = GetMoreData();
    // do your stuff
}
catch(Exception ex)
{
   // handle the exception
}
finally
{
   // close the reader
   dr.Dispose();
}

Edit

不错的评论JotaBe

但如果他实现一个返回 DataReader 的方法,则应在该方法的调用者中使用 using 。因此无法保证 DataReader 已关闭。

我不建议退货SqlDataReader但如果你想这样做,你需要这样做

SqlDataReader reader;
try
{
   reader = methodThatReturnsAReader();
}
catch(Exception ex)
{
   // handle the exception
}
finally
{
   // close the reader
   reader.Dispose();
}

更多信息

  • MSDN - IDisposable 接口 http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
  • MSDN - SqlDataReader 类 http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关闭 SQLDataReader - 如何判断它们是否已关闭? 的相关文章

随机推荐