Closing SQLDataReaders - how do you know if they are closed?

I find that I am having problems with the connection pool to the website, and I am in the process of tracking them. I know one thing I need to look for to make sure that any SQLDataReaders are closed, and I went, although I am sure that they are. One of the questions that arose in my head concerned the methods that return SQLDataReaders and how they are closed (or not).

So, here is how I have the settings and some example methods:

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);
}

then I have a method that uses 'ExecuteReader ()'

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

Now say that I have another method that calls "GetData". I obviously simplified things.

public static SqlDataReader GetMoreData()
{
  return GetData;
}

So my question is when I call "GetMoreData" as follows

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

Are all my SqlDataReaders and connections closed correctly?

Thank!

+3
4

SqlDataReader IDisposable. , IDisposable, Dispose using , .

IDisposable Interface. .

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

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

JotaBe

, DataReader, . , , DataReader .

SqlDataReader, ,

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

+4

, , dr.Close() ( ), , . , , , try/finally, finally dr.Close().

using, IDisposable, SqlDataReader.

+2

DataReader . DataReader . , DataReader , , .

, .

, DataReader .

, , , , , DataReader. .

0

using, SqlDataReader dr = GetMoreData(), , , GetMoreData(). , , .

Microsoft:

" DataSet, :

- .

:

" DataReader, :

- , -, .

, -. , DataSets , DataReaders, :

  • (, ) ()
  • - DataTable DataRow DataSet?

DataReaders , , .

0

All Articles