A basic example of garbage collection
suggest changeGiven the following class:
public class FinalizableObject
{
public FinalizableObject()
{
Console.WriteLine("Instance initialized");
}
~FinalizableObject()
{
Console.WriteLine("Instance finalized");
}
}
A program that creates an instance, even without using it:
new FinalizableObject(); // Object instantiated, ready to be used
Produces the following output:
Instance initialized
If nothing else happens, the object is not finalized until the program ends (which frees all objects on the managed heap, finalizing these in the process).
It is possible to force the garbage collector to run at a given point. GC.Collect only queues finalizers; GC.WaitForPendingFinalizers waits until they have run:
new FinalizableObject(); // Object instantiated, ready to be used
GC.Collect();
GC.WaitForPendingFinalizers();
Which produces the following result:
Instance initialized
Instance finalized
This time, once the garbage collector was invoked and pending finalizers ran, the unused (aka “dead”) object was finalized and freed from the managed heap.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents