How frowned-upon is not doing *.Close()?

T

TJ

Hello all.

I was wondering... I'm trying my hand at writing an MVC app in .NET
2.0. I'm using code-behind to implement pretty much all my logic, and I
was wondering, how bad of a practice is it to *not* use .Close(), such
as:

public void MenuView() {
// generate menu based on Uid in sesssion

// passes back strings
string sCmd = "[sp_GetMenuItemsByUid] @uid = " +
this.sm.GetUid();
SqlCommand oCmd = new SqlCommand(sCmd, this.oConn);

this.oConn.Open();

SqlDataReader oReader = oCmd.ExecuteReader();

this.qr.AddResult("menu", oReader);
//this.oConn.Close();
}

What I'm trying to do here is pass back a handle to the SqlDataReader
oReader in the .aspx page. In order for me to be able to access the
data reader, however, I need to keep the connection open after exiting
this function.

So I was wondering... is it okay for me to depend on garbage collector
to clean up my garbage, per se? Or should I still figure out a way to
ensure closure of this resource by coding up a destructor? Any thoughts
on this are appreciated.

Thanks in advance!
-TJ
 
C

Cowboy \(Gregory A. Beamer\)

I would aim for Dispose() instead. How bad is it to not do either? I would
say very bad, as you are putting extra weight on the GC, for no real reason.
If you must, I am sure it will do fine, but I would not adopt that pattern.
 
M

Mark Rae

What I'm trying to do here is pass back a handle to the SqlDataReader
oReader in the .aspx page. In order for me to be able to access the
data reader, however, I need to keep the connection open after exiting
this function.
Yes.

So I was wondering... is it okay for me to depend on garbage collector
to clean up my garbage, per se?

NO! Absolutely not! You have no idea when the GC is going to run - it might
be minutes or hours later... Leaving database connections open for longer
than absolutely necessary is a sure-fire way of throttling your web app's
performance.
Or should I still figure out a way to ensure closure of this resource by
coding up a destructor?

Luckily you don't have to, because Microsoft have already done it for you.

Simply change:

SqlDataReader oReader = oCmd.ExecuteReader();

to

SqlDataReader oReader = oCmd.ExecuteReader(CommandBehavior.CloseConnection);

http://www.google.co.uk/search?sour...8,GGLG:en&q="CommandBehavior.CloseConnection"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,190
Latest member
ClayE7480

Latest Threads

Top