Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The cost of finalize in .Net

(1) I've read a lot of questions about IDisposable where the answers recommend not using Finalize unless you really need to because of the process time involved.
What I haven't seen is how much this cost is and how often it's paid. Every millisecond? second? hour, day etc.

(2) Also, it seems to me that Finalize is handy when its not always known if an object can be disposed. For instance, the framework font class. A control can't dispose of it because it doesn't know if the font is shared. The font is usually created at design time so the user won't know to dispose it, therefore finalize kicks in to finally get rid of it when there are no references left. Is that a correct impression?

like image 556
Jules Avatar asked Jun 15 '10 13:06

Jules


People also ask

What is Finalize method in C#?

The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed. The method is protected and therefore is accessible only through this class or through a derived class.

What is Dispose () and Finalize ()?

Finalize is the backstop method, called by the garbage collector when it reclaims an object. Dispose is the "deterministic cleanup" method, called by applications to release valuable native resources (window handles, database connections, etc.)

What is the importance of finalize () method?

finalize() method in Java is a method of the Object class that is used to perform cleanup activity before destroying any object. It is called by Garbage collector before destroying the objects from memory. finalize() method is called by default for every object before its deletion.

What is the difference between Finalize () and garbage collector?

System. gc() forces the garbage collector to run, while the Finalize() method of your object defines what garbage collector should do when collecting this specific object.


2 Answers

The main problem with finalize is that it blocks an object from being garbage collected. Instead, the finalizer is called, and the object collected "on the next run". Well, technically IIRC the finalizer runs a list of objects in a separate thread. Anyhow, this is not an "every ms" issue, more an "multiple GC runs needed to get rid of the objects.

like image 157
TomTom Avatar answered Sep 24 '22 12:09

TomTom


Finalize is conceptually different than Dispose. Finalize can only free unmanaged resources. Dispose can free managed and unmanaged resources. You should use each as appropriate. (Note that a class with a Finalizer should always implement IDisposable).

Dispose must be called explicitly; Finalize can only be called by the GC.

Update: See my blog post on How to Implement IDisposable and Finalizers: 3 Easy Rules.

like image 35
Stephen Cleary Avatar answered Sep 24 '22 12:09

Stephen Cleary