Question on Disposing of Resources

  • Thread starter Thread starter Joe Keller
  • Start date Start date
J

Joe Keller

Hello,

In a custom class, is it better to dispose of resources that the class
allocated in the "destructor" of the custom or override the "Dispose()"
method?

Or, is there a more appropriate location altogether?

Thanks!

Joe
 
OK - can do - just curious, however...why not release resources in the
destructor?

Joe
 
The way I see it is that if the resource release code is in the protected
Dispose method then this method can be called by either the destructor or
the public Dispose method - giving the "client" code the opportunity to
cleanup without the penalty of finalization. And if the resource release
code was in the destructor, and you wanted the "client" code to have control
over releasing the unmanaged resources, then you couldn't expose the
destructor for them to call and you couldn't call it yourself internally, so
you would have to wait until finalization to actually release these
resources. Placing the cleanup code in the protected Dispose method just
seems to make things more flexible.
 
Also keep in mind that .NET doesn't support deterministic finalization,
meaning that if the class goes out of scope it is not guaranteed that it
will be destroyed immediately. The GC will do it whenever it fills like
doing it.
 
An interesting point Tim. Personally I usually use the dtor, simply as a
holdover habit from C++. I probably should start using Dispose instead.
 

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

Back
Top