2

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?

Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
zmbq
  • 38,013
  • 14
  • 101
  • 171
  • **the Dispose method threw an exception while being called from the finalizer** : i don't think it's true because you are supressing the `Finalizer` from `Dispose` method when it is called with `true` parameter. – Sudhakar Tillapudi Mar 23 '14 at 12:15
  • 2
    "None of the objects use unmanaged resources" - Then why did you implement IDisposable in the first place? Also, check out this question: http://stackoverflow.com/q/3882804/1974021 – DasKrümelmonster Mar 23 '14 at 12:16
  • I implement IDisposable to let people write `using(new MyObj())...` and have the cleanup code run when leaving the using block. – zmbq Mar 23 '14 at 12:21
  • The problem we've encountered was that the constructor of the IDisposable interface threw an exception, so Dispose wasn't called, and the finalizer threw another exception... – zmbq Mar 23 '14 at 12:22

1 Answers1

2

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

Community
  • 1
  • 1
KevinS
  • 242
  • 1
  • 7