Garbage Collection

M

Mr Flibble

If I dont call the close method on objects I use will they still be
garbage collected ? I'm guessing they are in which case, is there any
point in calling the close method ? In code on Microsoft's site I've
seen :

// Cleanup the streams and the response.
reader.Close ();
dataStream.Close ();
response.Close ();

etc..

but in code published elsewhere on the net, or even here, I dont see
this habit being effected.

So.. comments please :) Should I go through my code and make sure I'm
closing/quitting all objects that support these methods , or just leave
it to the garbage collector to destroy them.

El Flibble
 
C

Cowboy \(Gregory A. Beamer\)

Should you? Yes. If the object has a Dispose() method, all the better.

Will the objects get cleaned anyway? Possibly, when they fall out of scope.
This is esp. true in web apps, which are stateless. It is possible, however,
that you will lock up memory for a long time with non-closed objects, esp
those that have COM libraries beneath them (which is more than you might
imagine).

As a rule, explicit coding is better than implicit coding. Make sure you
have purpose for your code.

--
Gregory A. Beamer

*************************************************
Think Outside the Box!
*************************************************
 
M

Marc Gravell

In short - yes; objects should be promptly closed and disposed (as
appropriate) to ensure both that any resources (particularly unmanaged) are
released as soon as possible.

For unmanaged objects, finalizers (via GC) will probably clean things up
eventually (maybe), but it is far better to programatically release things
early; this can avoid intermittent timing bugs, whereby some operations work
or don't work based entirely on the GC, which is out of our hands (plus it
means we minimise our footprint); consider a FileStream; if I don't Close
this promptly, then another block of code opening that file may work or
crash, depending on whether my FileStream has been finalized. Think about
connections, graphics, etc as well. All limited resources - why keep them
open longer than necessary?

Marc
 
S

Stoitcho Goutsev \(100\)

GC doesn't care if you have closed the reader on not. GC will collect the
object as long as they are not referenced from anywhere in the code. Further
more usually these objects has finalizer so before the GC collect the object
they will be closed by the finalizer.
 

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

Top