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

  • Thread starter Thread starter TJ
  • Start date Start date
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
 
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.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com

*************************************************
Think outside of the box!
*************************************************
 
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"
 
Back
Top