What is Finalizer in .NET? - Finalizer in .NET are the methods that help in cleanup the code that is executed just before the object is garbage collected.
- The methods of Finalizer are Dispose and Finalize.
- When we call Dispose method it cleans managed as well as unmanaged resources and when we call Finalize method, it clears only the unmanaged resources.
- 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.
- The Object class provides no implementation for the Finalize method, and the garbage collector does not mark types derived from Object for finalization unless they override the Finalize method.
- If a type does override the Finalize method, the garbage collector adds an entry for each instance of the type to an internal structure called the finalization queue.
- The finalization queue contains entries for all the objects in the managed heap whose finalization code must run before the garbage collector can reclaim their memory.
The garbage collector then calls the Finalize method automatically under the following conditions:
1. After the garbage collector has discovered that an object is inaccessible, unless the object has been exempted from finalization by a call to the GC.SuppressFinalize method.
2. During shutdown of an application domain, unless the object is exempt from finalization. During shutdown, even objects that are still accessible are finalized.
|