I think I am missing something fundamental and hope you can help. Below code creates an object, removes the reference and call the garbage collector. My expectation was that SomeClass's finalizer would be called when standing in Readline. It doesn't. I've tried calling GC.Collect in a loop, adding some Sleep() calls to have the finalizer thread started. Does not happen.
Only when the Main ends the finalizer is hit, but surprisingly it is hit twice. What am i missing?
class Program
{
public static void Main(string[] args)
{
SomeClass some = new SomeClass("Hello World!");
some = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Done");
Console.ReadLine();
}
}
class SomeClass
{
string ss;
public SomeClass(string s) { ss = s; }
~SomeClass()
{
var hash = this.GetHashCode();
}
}
Addendum
There is a difference in running a program in debug mode versus release mode. The below program produces in debug mode Start - Done - Finalize
whereas in release mode the logfile shows Start - Finalize - Done
. The latter is what I expected.
class Program
{
private static string logfile = @"c:\temp\log.txt";
public static void Main(string[] args)
{
File.WriteAllText(logfile, "Start\n");
SomeClass some = new SomeClass("Hello World!");
some = null;
GC.Collect();
GC.WaitForPendingFinalizers();
File.AppendAllText(logfile, "Done\n");
}
}
class SomeClass
{
private static string logfile = @"c:\temp\log.txt";
public string SomeString { get; set; }
public SomeClass(string s) { SomeString = s; }
~SomeClass()
{
File.AppendAllText(logfile, "Finalize\n");
}
}