dispose vs finalize

  • Thread starter Thread starter Bhuwan Bhaskar
  • Start date Start date
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
 
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
 
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!
|
*************************************************
 
Back
Top