Re: GC and dispose
- From: "Carl Daniel [VC++ MVP]" <cpdaniel_remove_this_and_nospam@xxxxxxxxxxxxxxx>
- Date: Wed, 21 Jun 2006 16:12:20 -0700
"Göran Andersson" <guffa@xxxxxxxxx> wrote in message
news:evglUFYlGHA.2128@xxxxxxxxxxxxxxxxxxxxxxx
Markus Stoeger wrote:
Simon Hart wrote:
Agree. We often use the Dispose (IDisposable) for cleaning managed
resources as well as unmanaged. We tend to use the Finalizer
(Destructor) for unmanaged deallocation.
Could you explain why you prefer the finalizer instead of a manual call
to Dispose for freeing unmanaged resources?
As far as I know you can never tell when the GC will finalize an object.
So it might keep floating around forever as well. Which means that you
could run out of handles for example.
Maybe I've misunderstood something behind GC and the finalizer?.
Max
No, that is correct.
The Dispose method should be used to free resources. The finalizer should
call Dispose as a backup if the program failed to call it.
More specifically, the recommended structure for Finalize and Dispose is:
class C : IDisposable
{
void IDisposable.Dispose()
{
Dispose(true);
}
~C()
{
Dispose(false)
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources here
GC.SuppressFinalize(this);
}
// free unmanaged resources here
}
}
The C++/CLI compiler automatically implements this structure, while in C#/VB
you have to do it yourself. Current versions of FxCop will raise warnings
if your class implements IDisposable but doesn't do it this way.
Of course, if your class cannot be derived from, then there's no need for
Dispose(bool) to be virtual.
-cd
-cd
.
- Follow-Ups:
- Re: GC and dispose
- From: Michael D. Ober
- Re: GC and dispose
- References:
- GC and dispose
- From: Petros Amiridis
- Re: GC and dispose
- From: Phil Wilson
- Re: GC and dispose
- From: Petros Amiridis
- Re: GC and dispose
- From: Daniel Billingsley
- Re: GC and dispose
- From: Carl Daniel [VC++ MVP]
- Re: GC and dispose
- From: Simon Hart
- Re: GC and dispose
- From: Markus Stoeger
- Re: GC and dispose
- From: Göran Andersson
- GC and dispose
- Prev by Date: Re: When is Debug.Assert pertinent to use ?
- Next by Date: Re: fast file count method?
- Previous by thread: Re: GC and dispose
- Next by thread: Re: GC and dispose
- Index(es):
Relevant Pages
|