Throwing an exception in the finalizer to force the use of Dispose calls:

Here is a typical implementation of IDisposable, which I think is recommended:

~SomeClass() {
    Dispose(false);
}

public void Dispose() {
    GC.SuppressFinalize(this);
    Dispose(true);
}

protected virtual void Dispose(bool isDisposing) {
    if(isDisposing) {
        // Dispose managed resources that implement IDisposable.
    }
    // Release unmanaged resources.
}

Now, in my opinion, the idea behind the finalizer is that if I don't call Dispose, my unmanaged resources will be released properly. However, to my knowledge, it is generally agreed that not calling Dispose on an object that implements IDisposable is probably a mistake.

Is there any special reason for not hugging this completely and doing it instead?

~SomeClass() {
    throw new NotImplementedException("Dispose should always be called on this object.");
}

public virtual void Dispose() {
    GC.SuppressFinalize(this);

    // Dispose managed resources that implement IDisposable.

    // Release unmanaged resources.
}
+4
source share
4 answers

.NET 2.0 , , Finalizer , .

, Finalizer , . , Dispose() (Thread abort,...), - , , Finalizer .

+8

.

, , ( , ), , .

, (, ), - ; , , , . , , , , , .

+2

- , . . ExecutionEngine, , , OutOfMemory (OOM) .. , - , .

+1

, , , , , , IIS7.5 Debug.Fail , . :

I only do this in the debug build , as it will not have any benefit for the release build. In addition, it removes the slow finalizer from classes that do not contain unmanaged resources directly.

public void Dispose()
{
    // Do your dispose stuff here
#if DEBUG
    GC.SuppressFinalize(this);
}
~MyClass()
{   throw new ObjectNotDisposedException(); // This class is not intended to be used without Dispose.
#endif
}

There are times when a missing order can really intimidate an application, for example. remote transaction context. Termination in this case is no worse and will be on the lazy nerves of the developers. I always prefer to return problems to their source.

0
source

All Articles