Help: Cleaning up: Close vs Dispose vs Set to Nothing

  • Thread starter Thread starter VB Programmer
  • Start date Start date
V

VB Programmer

1. When cleaning up db connections, datareaders, datasets, sqlcommands,
etc.. what should you do? (Close or dispose or set it to Nothing, etc...?)

2. What are the differences between Close, Dispose, and setting it to
Nothing?

3. Is this code typically handled in the Finally part?

Thanks!
 
William Ryan said:
Disposing something marks it so that the next time a
Garbage collection occurs, it'll be collected.

Pardon me, but this is not the case. Disposing something indicates to the
object that you're done with it. What that means depends on the object. In
general, it means that the object will get rid of any expensive resources it
was keeping around until the next time you use it. When you call Dispose, it
tells the object that there will not be a next time, so it can get rid of
them.

When a Garbage Collection occurs, it will collect whatever objects aren't
being referenced (depending, in part, or whether they have a Finalize
method).
If you are going to reuse a connection, simply close it.
If you won't use it again, go ahead and dispose of it.

It is my understanding that for objects which implement a Close method,
Close is the same as Dispose. I've read that a Close method should be
implemented in cases where it's "traditional" to have a "Close" method. So,
streams and database connections will have a "Close" method.
The distinction between Closing and Disposing is hard to
draw b/c only some things ever get closed, buy everything
can conceivably be disposed.

Not all objects implement a Displose method.
 
1) Close, close the connection.

2) Dispose, frees unmanaged resource, in case of a Connection object, it
DOES run the close. (can be used with using)

3) Setting to Null (or nothing) does nothing :), well, it marks the object
as finished with, but will NOT close the connection until the garbage
collects the resource.

Setting thing to null will speed up the GC, when I say speed up I don't mean
it will run sooner, I mean it will take less time to collect.

Personally, I use DISPOSE as I use C# and use the uses statement.

Steve
 
Back
Top