What are the finalists for?

I have been programming in .NET for four years (mainly in C #) and I use IDiposable extensively, but I still have to find a finalist. What are the finalists for?

+7
c # finalizer
source share
5 answers

The finalizer is the latest attempt to verify that something is cleaned up correctly and is usually reserved for objects that wrap unmanaged resources , such as unmanaged descriptors, etc. that will not collect garbage.

It’s rare to write a finalizer. Fortunately (and unlike IDisposable ), finalizers do not need to be propagated; so if you have a ClassA with a finalizer and a ClassB that wraps ClassA , then ClassB does not need a finalizer, but it is likely that ClassA and ClassB will implement IDisposable .

For managed code, usually IDisposable . Even if you do not clean it correctly, ultimately managed objects will be collected (provided that they are released).

+10
source share

Finalizers are only intended to free unmanaged resources such as handwritten GDI files, for example. Unless you allocate unmanaged resources, you don’t need finalizers. In general, it is a bad idea to touch any managed object in the finalizer, because the completion order is not guaranteed.

Another useful method using the finalizer is to claim that Dispose is called when the application needs it. This can help catch coding errors in the DEBUG assembly:

 void Dispose() { GC.SuppressFinalize(this); } #if DEBUG ~MyClass() { Debug.Fail("Dispose was not called."); } #endif 
+4
source share

Finalizers are meant as a mechanism for releasing resources not controlled by the garbage collector, as an unmanaged descriptor. Although Dispose can do this, it is not guaranteed that the consumer will call him.

+2
source share

Finalizers are designed to clear resources if they have not been deleted.

IE, nothing guarantees that you ever called Dispose (), but Finalizer is automatically called by the garbage collector.

You should not rely on this functionality, since there is no guarantee when (or if) garbage collection will reach your facility.

+1
source share

Wikipedia says :

... a finalizer is a piece of code that ensures certain necessary actions are taken when the acquired resource ... is no longer used [because the owner of the object was garbage collected]

And if you do not use the finalizer when writing IDisposables, you may well have memory leaks, because there is no guarantee that the owner will actually call Dispose ().

MS myself recommend you write something similar to this in your artists:

  public void Dispose() { this.Dispose(true); } protected virtual void Dispose(bool disposing) { if (!this.isDisposed) { if (disposing) { GC.SuppressFinalize(this); } } //Dispose of resources here this.isDisposed = true; } ~DisposableSafe() { this.Dispose(false); } private bool isDisposed = false; 

Personally, I cannot stand copy-paste, so I tend to wrap it in an abstract class for reuse.

+1
source share

All Articles