using statment with sql connection

  • Thread starter Thread starter John J. Hughes II
  • Start date Start date
J

John J. Hughes II

I was wondering about the follow code. I know that dispose is called on an
object when it leaves the using clause but was also wondering if the closed
statement was called on objects like Sql Connection and Data Readers?
Basically will I have problem or leave an object in memory if the closed is
not called below?

using(SqlConnection con = new SqlConnection())
{
con.Open();
using(SqlCommand cmd = con.CreateCommand)
{
... set up
using(SqlDataReader dr = cmd.ExecuteDateReader())
{
while(dr.Read())
..... do something
}
}
}

Regards,
John
 
John, in both cases the object's Close( ) methods are called in their
respective Dispose( ) methods. In a situation where you don't wrap your code
in using statements, then I suppose not calling the Close methods of these
objects only become a problem if they are long lived or objects scoped as
members of some class that is long lived, otherwise when the objects fall
out of scope they should be disposed of.

Hope this helps.
Cordell Lawrence
Teleios Systems Ltd.
 
Hi,

The close operation will be performed when the Dispose event, now as this
is not deterministic you don't have control of when will that happen,
therefore it's advised that you close your connectin as soon as you finish
with it.

cheers,
 
Ignacio said:
Hi,

The close operation will be performed when the Dispose event, now as this
is not deterministic you don't have control of when will that happen,
therefore it's advised that you close your connectin as soon as you finish
with it.

?? I thought Disposed was deterministic, only finalize is not
deterministic. In his example Dispose should be called when the using block
is exited.
 
Ok, I had a feeling about that. Basically I could end up with a bunch of
open connection waiting for the system to get around to closing them which
could be a problem.

Thanks,
John
 
Thanks,
John

Cordell Lawrence said:
John, in both cases the object's Close( ) methods are called in their
respective Dispose( ) methods. In a situation where you don't wrap your
code
in using statements, then I suppose not calling the Close methods of these
objects only become a problem if they are long lived or objects scoped as
members of some class that is long lived, otherwise when the objects fall
out of scope they should be disposed of.

Hope this helps.
Cordell Lawrence
Teleios Systems Ltd.
 
Hi Tom,

My mistake, you are 100% right, Dispose is deterministic

sorry for the error, going to get some expresso in my bloodstream :)

cheers,
 
So basically if I can stop writing close on these short read commands,
that's nice, saves a lot of finally statments in my code.

Regards,
John
 
Back
Top