Object Finalization
.NET objects are never told when they become garbage; they are simply overwritten when the managed heap is compacted. This presents you with a problem: if the object holds expensive resources (files, connections, communication ports, data structures, synchronization handles, and so on), how can it dispose of and release these resources? To address this problem, .NET provides object finalization
. If the object has specific cleanup to do, it should implement a method called Finalize(), defined as:
protected void Finalize();
When the garbage collector decides that an object is garbage, it checks the object metadata. If the object implements the Finalize() method, the garbage collector doesn’t destroy the object. Instead, the garbage collector marks the object as reachable (so it will not be overwritten by heap compaction), then moves the object from its original graph to a special queue called the finalization queue
. This queue is essentially just another object graph, and the root of the queue keeps the object reachable. The garbage collector then proceeds with collecting the garbage and compacting the heap. Meanwhile, a separate thread iterates over all the objects in the finalization queue, calling the Finalize() method on each and letting the objects do their cleanup. After calling Finalize(), the garbage collector removes the object from the queue.
Explicit Garbage Collection
You can trigger garbage collection explicitly with the static method Collect() of ...