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
Peter Duniho - 30 Mar 2008 01:04 GMT
> 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.
Always use Dispose().
Finalize is there for the run-time, as a "fail-safe" mechanism for code
that forgets to call Dispose(). It's not for you to call directly.
Pete
Henning Krause [MVP - Exchange] - 30 Mar 2008 11:55 GMT
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
> Hi,
>
[quoted text clipped - 4 lines]
> Regards,
> Bhuwan
Cowboy (Gregory A. Beamer) - 31 Mar 2008 03:03 GMT
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.

Signature
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!
*************************************************
> Hi,
>
[quoted text clipped - 4 lines]
> Regards,
> Bhuwan