Forum Moderators: open

Message Too Old, No Replies

c# datareader cleaner

anybody know of any open object cleaners

         

trimmer80

10:54 pm on Sep 22, 2005 (gmt 0)

10+ Year Member



I am working with a substancial amount of code that uses oledbdatareaders. I am looking for code that i can implement in the 'finally' clause that will find and close any open datareaders.
Does anybody know of code that achieves this?

Easy_Coder

11:24 pm on Sep 22, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you make use of 'using' then .net will automatically dispose the objects for you.

Because it's a DataReader you can't close the connection even if you attempt to close it in a try,catch finally block. The client waill gak becuase it needs the connection to be open to uncork the datareader.

The key to shutting down the connection is to make sure that the CommandBehavior gets passed into the Execute Reader method (see code below). The same can be used with the OleDbDataReader too.

I just chased this down a few weeks ago and until I passed CommandBehavior.CloseConnection into ExecuteReader one of my applications was leaving connections open on the database and they would grow throughout the day.

I just scratched this out so now warranty but it demonstrates 'using' :)

SqlDataReader r;

using(SqlConnection mCNN = new SqlConnection("yourconnstring"))
{
using(SqlCommand mCMD = new SqlCommand("sprocName", mCNN))
{
mCmd.CommandType.CommandType = CommandType.StoredProcedure;

try
{
mCMD.Open();
r = mCMD.ExecuteReader(CommandBehavior.CloseConnection);
}
catch(Exception se)
{
// Do something with this error
se.ToString();
}
}
}

trimmer80

12:00 am on Sep 23, 2005 (gmt 0)

10+ Year Member



cheers,
I was looking for an easy fix, but this is the closest ill find.
Thanks v.much

Easy_Coder

12:06 am on Sep 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



the documentation actually indicates that the connection will shut down when firing reader.close() but I've observed differently...