top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How can we suppress a finalize method?

+5 votes
443 views
How can we suppress a finalize method?
posted Sep 22, 2015 by Jdk

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

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
}
answer Sep 23, 2015 by Manikandan J
Similar Questions
0 votes

As we know FinalizerDaemon is calling finalizer methods of GCs/Dead objects, so is it possible to show the classname of the finalized object?

+4 votes

When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views?

...