Compartilhar via


Dispose/Finalize notes

When to implement a finalizer:

 

You should only implement a finalizer when you are implying that that the class encapsulates unmanaged resources, which, in other words, means you’re dealing with resources that the runtime’s garbage collector is not aware of. In this finalizer, you should clean up those unmanaged resources, otherwise memory leaks could occur when the garbage collector collects the object.

 

If your class has a finalizer, it should also implement IDisposable. Since object destruction is non-deterministic, theoretically, your objects could be sitting around for an infinite amount of time. A disposal instrument will allow the client programmer to clean up resources that are no longer referenced to immediately.

 

In many cases, the finalizer invokes the Dispose method.

 

https://msdn.microsoft.com/msdnmag/issues/04/05/NETMatters/

 

Disposing, but not finalizing:

 

If your class encapsulates any objects that have a resource-freeing mechanism, chances are you’re indirectly holding onto some unmanaged resources. You should implement IDisposable and dispose of those objects accordingly.

 

For example, if you have a class that encapsulates an Image object, which undoubtedly holds onto unmanaged resources, you will want to dispose of this object in your class’ Dispose() method.