I'm trying to write a unit test for testing a memory leak. Steps to Reproduce:
TestClass test = new TestClass();
WeakReference reference = new WeakReference(test, true);
test = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Debug.Assert(reference.Target == null, "Memory Leak"); // This works
//Replacing the above line with following, I see "Memory Leak" being printed.
if (reference.Target != null)
{
Console.WriteLine("Memory Leak");
}
I added a finalizer:
~TestClass() { Console.WriteLine("TestClass instance finalized");}
and I noticed that the finalizer gets called as part of GC commands in the Assert case but when I replace it with if condition, the finalizer doesn't gets called as part of the GC commands and hence the reference's target is still alive. The finalizer gets called only before the program exists.
Expected Behavior:
if(reference.Target != null) Console.WriteLine("Memory Leak");
should work.
Actual Behavior:
Debug.Assert(reference.Target == null, "Memory Leak");
works but
if(reference.Target != null) Console.WriteLine("Memory Leak");
doesn't works as it prints "Memory Leak"