Why do we need parameter disposing in the below code snippet.
Moreover we invoke dispose with false, in finalizer and it won’t release or do the clean up.
So what if dispose never get called?
Isn’t dispose always get called before finalizer?
using System;
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
**//Do we really need this condition?
if (disposing)**
{
// called via myClass.Dispose().
// OK to use any private object references
}
disposed = true;
}
}
public void Dispose()
// Implement IDisposable
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass() // the finalizer
{
//why do we need to call with false?
Dispose(false);
}
}
In other words, why not?
using System;
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool suppressFinalize)
{
if (!disposed)
{
//Do we really need this condition?
// called via myClass.Dispose().
// OK to use any private object references
disposed = true;
}
if (!suppressFinalize)
{
GC.SuppressFinalize(this);
}
}
public void Dispose()
// Implement IDisposable
{
Dispose(true);
}
~MyClass() // the finalizer
{
//why do we need to call with false?
Dispose(false);
}
}
In fact, do I really need finalizer? Why not this?
using System;
public class MyClass : IDisposable
{
public void Dispose()
// Implement IDisposable
{
//just do the cleanup and release resources
GC.SuppressFinalize(this);
}
}
Indeed – it will assume that other classes handle their own cleanup in that case, and only do the clean-up of direct unmanaged resources.
Then the finalizer will be called, and it will clean up any direct unmanaged resources, but not worry about indirect resources.
Not if no-one calls it for whatever reason.
I think this pattern is more complicated than it needs to be, as it’s trying to account for classes which act as base classes for other classes which might need finalizers. Seal your classes and you can just implement exactly what you’d expect to 🙂
You might also want to read Joe Duffy’s “Never write a finalizer again” blog post and the long explanation of the pattern.