The default dispose implementation pattern (as shown in IDisposable’s help page) also adds the line GC.SuppressFinalize(this); to the Dispose() method. What does this method do and why do we need it?
GC.SuppressFinalize() simply prevents the finalizer from being called. Since the finalizer’s only task is to free unmanaged data, it doesn’t need to be called if Dispose() was already called (and already freed all unmanaged data by calling the finalizer). Using GC.SuppressFinalize() give a small performance improvement but nothing more.
In C# the Dispose() method changes like this:
public void Dispose() {
Dipose(true);
GC.SuppressFinalize(this);
}
In C++/CLI, the destructor doesn’t change at all. That’s because the C++/CLI compiler automatically adds this code line to the destructor. (You can read about this and see a decompiled destructor here. Search for “SuppressFinalize”.)
~DataContainer() {
if (m_isDisposed)
return;
delete m_managedData; // dispose managed data
this->!DataContainer(); // call finalizer
m_isDisposed = true;
// GC.SuppressFinalize(this) is automatically inserted here
}