I've recently had to start writing C# (moving from C++), and one of the first discussions I had today with peers was about IDisposable, as the CLR collects garbage own it's own, the Destructor (or Finalizer) doesn't always get called immediately (as it does in C++).
Here's a quick example of the pattern implemented as I understand it (for reference):
Why does the IDisposable interface only implement Dispose()? It seems like the pattern emphasizes telling the Garbage Collector to remove this class's destructor (finalizer) from it's queue when called explicitly by Dispose(), and it also encourages having a Disposing(bool disposing) function so that the user can clean up managed/unmanaged resources safely.
Lastly, it keeps track of stupid human tricks with private boolean _disposed, in the event that a user would call Dispose() explicitly on their own, and then leave a try/catch block (or using{} block) and have Dispose() called again.
TL;DR, why doesn't IDisposable force an implementation of:
I expect there's good discussion on this (not always necessary to clean up managed resources, different patterns for locking, etc.) but I'm curious what others with more experience with IDisposable think.
Here's a quick example of the pattern implemented as I understand it (for reference):
Code:
sealed public class Whatever
{
private Boolean _disposed;
public Whatever()
{
this._disposed = false;
}
~Destructor()
{
Dispose(false);
}
public void Dispose()
{
Dipose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!this._disposed)
{
this._disposed = true;
if (disposing)
{
// Free managed resources, object references, etc.
}
// Free unmanaged resources, pointers/handles, etc.
}
}
}
Why does the IDisposable interface only implement Dispose()? It seems like the pattern emphasizes telling the Garbage Collector to remove this class's destructor (finalizer) from it's queue when called explicitly by Dispose(), and it also encourages having a Disposing(bool disposing) function so that the user can clean up managed/unmanaged resources safely.
Lastly, it keeps track of stupid human tricks with private boolean _disposed, in the event that a user would call Dispose() explicitly on their own, and then leave a try/catch block (or using{} block) and have Dispose() called again.
TL;DR, why doesn't IDisposable force an implementation of:
- private boolean _disposing
- Dispose(boolean disposing)
- Dispose() { Disposing(true); GC.SuppressFinalize(this); }
I expect there's good discussion on this (not always necessary to clean up managed resources, different patterns for locking, etc.) but I'm curious what others with more experience with IDisposable think.
Last edited: