I have a question about how to use Dispose()
and destructors. Reading some articles and the MSDN documentation, this seems to be the recommended way of implementing Dispose()
and destructors.
But I have two questions about this implementation, that you can read below:
class Testing : IDisposable
{
bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed) // only dispose once!
{
if (disposing)
{
// Not in destructor, OK to reference other objects
}
// perform cleanup for this object
}
_disposed = true;
}
public void Dispose()
{
Dispose(true);
// tell the GC not to finalize
GC.SuppressFinalize(this);
}
~Testing()
{
Dispose(false);
}
}
GC.SupressFinalize(this) on Dispose()
When the programmer uses using
or calls Dispose() explicity, our class is calling to GC.SupressFinalize(this)
. My question here is:
- What this exactly means? Will the object be collected but without calling the destructor?. I guess that the anwswer is yes since destructors are converted by the framework to a Finalize() call, but I'm not sure.
Finalizing without a Dispose() call
Suppose that the GC is going to clean our object but the programmer did not call Dispose()
- Why don't we dispose resource at this point? In other words, why can't we free resources on destructor?
What code must be executed in the if inside, and what outside?
if (!_disposed) // only dispose once! { if (disposing) { //What should I do here and why? } // And what here and why? }
Thanks in advance
SafeHandle
and managed resources usually don't require a finalizer. – Squeegee