Search code examples
c#idisposablefinalizer

What is the difference between the resources disposed in a finalizer to those released in dispose


This is a follow up question to this question:

Finalize/Dispose pattern in C#

So I understand that if I'm creating a class that uses unmanaged resources, I should dispose them. The answer in the linked question says that the finalizer disposes of the unmanaged resources. However, the Dispose(Boolean) method is also disposing of unmanaged resources:

protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // get rid of managed resources
        }   
        // get rid of unmanaged resources
    } 

So what is the difference between the disposal of the finalizer and the disposal of the dispose method?


Solution

  • The only reason you would use it (and its extremely controversial).

    1. A finalizer allows the clearing an object before it will be deleted by a garbage collector. (That's to say, The GC is responsible for calling it, and clearing the object from memory) If the developer forgot to call Dispose() method of an object, then it will be possible to free the unmanaged resources and thus, avoid the leak.

    There are many reasons not to, and many ways to get it wrong. In short there is seldom a reason why you need to do this, or want to do it