dispose vs finalize

B

Bhuwan Bhaskar

Hi,

I want to know, the difference between finalize and dispose? I know that
those methods release unmanaged resources. I am confused, when to use
dispose and when finalize.

Regards,
Bhuwan
 
H

Henning Krause [MVP - Exchange]

Hello,

an addendum to what Peter wrote:

If you have unmanaged resources in your class you usually impelement both: A
finalizer and a Dispose method, like this:

public class test: IDisposable {
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}

~test() {
Dispose(false);
}

protected virtual void Dispose(bool disposing) {
if (disposing) {
// Clean up managed resources, call Dispose methods of member
variables

return;
}
// Clean up unmanaged resources
}

This will ensure that the Dispose method is called exactly once: The
Dispose() method will remove the object from the finalizer queue. Otherwise
the finalizer is called.

But instead of writing your own destructor here, you should take a look at
the SafeHandle class; they wrap all this up quite nicely.

Kind regards,
Henning Krause
 
C

Cowboy \(Gregory A. Beamer\)

Unless you are working with Framework components, you should focus on
Dispose(). THere are some rare instances you might need to use Finalize, but
it is not guaranteed to be called until trash pickup, which will not happen
on all assemblies. This all has to do with how the garbage collector works,
but makes sense if you understand how the CLR works.

--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://gregorybeamer.spaces.live.com/lists/feed.rss

or just read it:
http://gregorybeamer.spaces.live.com/

*************************************************
| Think outside the box!
|
*************************************************
 

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