Hello friends, In this article I will discuss why we should be careful in using the Finalize method in C# and .NET programming. You should ponder below Finalize limitations in C# before adding it in your class.
Before reading the article you must be interested in below articles:
How to use Dispose And Finalize in C#
Dispose and Finalize Difference in C#
Finalize limitations in C# to consider before using
-
- Finalize will be called even if the constructor of the object throws an exception. We should be careful in for the constructors creation of the classes which have Finalize method.
Have a look at the below C# code. If there is no file present in the location provided, the constructor will throw an exception.
But still the the instance of the class will be kept in the Finalization list.
public class FileHandler { FileStream fs; public FileHandler() { fs = File.OpenRead("C:\\Test.txt"); } ~FileHandler() { fs.Close(); } }
Instead we can write the constructor as shown below
public FileHandler() { try { fs = File.OpenRead("C:\\Test.txt"); } catch (Exception) { GC.SuppressFinalize(this); } }
- Finalize object takes longer to allocate because pointers to these object must be placed in the Finalization list. This would not a big issue if we are creating only a couple of these objects. But if there is a bunch of these objects, the application can have visible impacts.
- Finalize objects get promoted to older generations, which increases memory pressure and prevents the object’s memory from being collected at the time the GC determines that object is garbage.
- Finalizable object cause your application to run slower since extra processing must occur for each object when collected.
- We have no control when Finalize method will execute. Finalize method runs when GC occurs, which may happen when your application requests more memory.
Also CLR doesn’t make any guarantee as to the order in which Finalize method are called, we should avoid writing a Finalize method that accesses other objects whose type defines a Finalize method, those types could have Finalize already. However it is perfectly ok to call value type as they don’t have Finalize implementation.
Leave a Reply