Domanda

In an almost 10 year old system, I've implemented several IDisposable implementations. Back in the old days, when I was younger and still foolish, the trend was to implement a finalizer as well:

class MyClass: IDisposable
{
    public void Dispose() { Dispose(true); }
    ~MyClass { Dispose(false); }

    private void Dispose(bool bDisposing)
    {
         ... dipose  ...
         if(bDisposing)
             GC.SupressFinalize(this);
    }
}

Finally, after almost a decade, this bit us - the Dispose method threw an exception while being called from the finalizer, and the process died unexpectedly and without warning.

I want to remove all the finalizers, and keep just the Dispose method that will dispose of the resources. Is there any reason to keep the finalizers around? None of the objects use unmanaged resources, so I'm pretty sure I won't get resource leaks. Right?

È stato utile?

Soluzione

The general advice on when you need a finalizer is: almost never. See Eric Lippert's response to the following question:

When should I create a destructor?

Whether your application will have leaks depends upon many things. However, if you have no unmanaged resources, and you are good about Dispose'ing classes that should be disposed, then you shouldn't have leaks.

On your comment above about running into an issue where a finalizer ran on an object that wasn't fully constructed: this is part of the reason why finalizers can be a dangerous thing. Writing a correct finalizer is a very difficult thing. If you really have resources that must always be cleaned up, you should be using a SafeHandle:

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle(v=vs.110).aspx

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top