Does the garbage collector shutdown after the entire Main method has finished executing or does it still run in the background to clean up all the objects the Main method has left over in the memory.
The garbage collector will run in the background at program exit to run pending finalizers, but if the finalizers take too long, it will give up and exit prematurely.
You can demonstrate this with the following program:
using System;
using System.Diagnostics;
using System.Threading;
namespace Demo
{
class Test
{
~Test()
{
Thread.Sleep(250);
Trace.WriteLine("In Test finalizer");
}
}
class Program
{
static void Main()
{
var t = new Test[20];
for (int i = 0; i < 20; ++i)
t[i] = new Test();
//t = null;
//GC.Collect();
//GC.WaitForPendingFinalizers();
}
}
}
Run that program under the debugger and you will see that only some of the 20 finalizers are actually run before the GC gives up.
However, you can ensure that all pending finalizers are completely run at the end of the program by calling
GC.Collect();
GC.WaitForPendingFinalizers()
If you uncomment the three commented-out lines at the end of Main() in the sample code above and run the program under the debugger again, you'll see that all 20 calls to the Test finalizer will be made.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With