[dba-VB] Close DB Connection

jwcolby jwcolby at colbyconsulting.com
Wed Dec 1 07:45:06 CST 2010


Vlad,

The destructor is not a class but (kind of) a method of the class.  The destructor is called when 
the last reference to the class is set to null, just as the constructor is called in the new 
MyClass().  By creating a destructor, and placing an explicit call to all unmanaged object's 
Dispose() methods, the dispose of all such unmanaged objects gets called immediately as the last 
pointer is set to null.

AFAICT (and I am no expert, so anyone else is free to jump in here) what really happens is that:

1) You create an instance to your class.
2) In your class you create a pointer to an unmanaged object such as a sql server connection.
3) You use your class
4) You do not explicitly call the dispose() of the connection but...
5) You set the last pointer to your class to null (or exit the block that defined your class)...

Now... the instance of your class still sits in memory until the GC decides it needs the memory that 
your class takes up, but it may be quite some time before it does so.

AFAICT when the GC actually gets around to disposing of the memory, it explicitly attempts to call 
Dispose() of any unmanaged object (ignoring errors if the unmanaged object does not have a dispose 
method) so *at that time* the unmanaged object is finally released.

By your creating a destructor and explicitly calling the unmanaged object's dispose() method in the 
destructor, the unmanaged object is released at the instant the last pointer to the class is set to 
null (when the containing block is exited).  Thus YOU decide the timing, rather than the GC deciding 
the timing.

This was an issue to me because I was creating thousands of connections in a very short period of 
time.  Because the GC decided I had lots of memory and it didn't need to take out the trash for long 
periods, I ran out of connections.

By explicitly creating destructors in every class that created a connection, and explicitly calling 
the dispose() of the connection (unmanaged object) in the destructor, I explicitly released the 
connection at the instant that the class was destroyed rather than when the GC ran, and my problems 
went away.

Or at least this is my understanding of the process.  What I know is that my problems went away when 
I did this.

It is a PITA to create the destructor and all the code to correctly manage it but once done you are 
gold (for that class).  Just remember to place calls to dispose() in the destructor for all 
unmanaged objects.

John W. Colby
www.ColbyConsulting.com

On 12/1/2010 8:16 AM, ACTEBS wrote:
> Hi John,
>
> Wow! I'm just returning to application development after a 5 years absence.
> Destructor and Constructor classes are just a little out of my realm at the
> moment.
>
> I need to find a good resource that outlines classes use in VB.Net. Do you
> know of any?
>
> Thanks
>
> Vlad



More information about the dba-VB mailing list