1
Reply

What is the significance of Finalize method in .NET? and Why is it preferred to not use finalize for clean up?

kalit sikka

kalit sikka

15y
9.9k
0
Reply

    It is better to read about garbage collection in Jeffrey Richter book CLR via C#. Brief cite from th book about Finalize method

    It's best if you avoid using a Finalize method for several reasons all related to performance:

    • Finalizable objects take longer to allocate because pointers to them must be placed on the finalization list (which I'll discuss in the "Finalization Internals" section a little later).

    • Finalizable objects get promoted to older generations, which increases memory pressure and prevents the object's memory from being collected at the time the garbage collector determines that the object is garbage. In addition, all objects referred to directly or indirectly by this object get promoted as well. (I'll talk about generations and promotions later in this chapter.)

    • Finalizable objects cause your application to run slower since extra processing must occur for each object when collected.

    Furthermore, be aware of the fact that you have no control over when the Finalize method will execute. Finalize methods run when a garbage collection occurs, which may happen when your application requests more memory. Also, the CLR doesn't make any guarantees as to the order in which Finalize methods are called, so you should avoid writing a Finalize method that accesses other objects whose type defines a Finalize method; those other objects could have been finalized already. However, it is perfectly OK to access value type instances or reference type objects that do not define a Finalize method. You also need to be careful when calling static methods because these methods can internally access objects that have been finalized, causing the behavior of the static method to become unpredictable.

    15y
    0