I came across this succinct (well as succinct as you can be when discussing this topic) and comprehensive description of Dispose and Finalize semantics and thought I'd re-post it for reference (the author mentions specific C# functions, but the underlying mechanism applies to all .NET languages):-
(credits go to itowlson @ codeproject)
Finalize is the backstop method, called by the garbage collector when it reclaims an object. Dispose is the "deterministic cleanup" method, called by applications to release valuable native resources (window handles, database connections, etc.) when they are no longer needed, rather than leaving them held indefinitely until the GC gets round to the object.
As the user of an object, you always use Dispose. Finalize is for the GC.
As the implementer of a class, if you hold managed resources that ought to be disposed, you implement Dispose. If you hold native resources, you implement both Dispose and Finalize, and both call a common method that releases the native resources. These idioms are typically combined through a private Dispose(bool disposing) method, which Dispose calls with true, and Finalize calls with false. This method always frees native resources, then checks the disposing parameter, and if it is true it disposes managed resources and calls GC.SuppressFinalize.
1 comment:
The simplest time tracker to help you get things done.
Post a Comment