jim said:
Why was a destructor (finalizer) included in the syntax
of C# if implementing IDisposable is the sure way to
release resources held by a class? If you were doing a
language from scratch would you include finalization
syntax or force users to to explicit cleanup using
IDisposable?
GC is non-derministic - because of this, there is no way to dertermine
when your objects will be collected. If you are holding on to
unmangaged resources (and in some special cases managed resources) this
can be a bad thing. So having finalizers alone is not enough to ensure
proper release of resources. By using IDisposable, you give your self
control over exactly when resources are released. This is a good thing,
because it brings a degree of determinism and also lets you avoid the
performance penalty incured by having a finalizer (it takes two passes
of the GC to release objects with finalizers).
Basically, the common implementation (especially when dealing with
unmanaged resources) is to have the finalizer and implemnt IDisposable.
This makes sure that your resources will be released eventually in
case a client inadvertantly forgets to call dispose. Of course,
normally in the dispose method you will see a call to
System.GC.SupressFinalize(this) - to avoid the preformance penalty that
would be incured when the object was GC'd...
HTH,
Tom Shelton