Destructor and Forced Garbage Collection in .NET Framework

Destructor :

In simple terms a destructor is a member that implements the actions required to destruct an instance of a class. The destructors enable the runtime system. Destructor method is called only by .Net frameworks Garbage Collector (GC).

Forced Garbage Collection :

Foced Garbage collection is executed by means of calling System.GC.Collect() method. The garbage collector checks to see if there are any objects in the heap that are no longer being used by the application(checking the references exist for an object).

class Person
{
public Person() //Constructor
{
Console.WriteLine("Person {0} constructor", GetHashCode());
}
~Person() //Destructor
{
Console.WriteLine("Person {0} finalizer", GetHashCode());
}
}



class GCDemo
{
static void Main(string[] args)
{
Person p = new Person(); // The constructor is invoked here.
p = null;
Console.WriteLine("The object p will not be used anymore ");
Person pc = new Person(); // The constructor is invoked here.
pc = null;
Console.WriteLine("The object pc will not be used anymore ");
GC.Collect(); // Force to collect.
Console.WriteLine("Now the carbage collection is called forcefully...");
GC.WaitForPendingFinalizers(); // Wait until it finish
}
}


Output:

Person 33156464 constructor
The object p will not be used anymore
Person 15645912 constructor
The object pc will not be used anymore
Now the carbage collection is called forcefully...
Person 33156464 finalizer
Person 15645912 finalizer

Conclusion:

  • Destructor methods are called after the garbage collection method executed.
  • Garbage collector destroys both person objects because reference "p" and "pc" is null.

No comments: