Steps to Reproduce:
This is my code:
using (TestClass test = new TestClass())
{
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
This is how I defined TestClass:
public class TestClass : IDisposable
{
public void Dispose()
{
Dispose(true);
//GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Console.WriteLine("Disposing TestClass.");
}
}
~TestClass()
{
Dispose(false);
Console.WriteLine("TestClass Finalizer called");
}
}
Expected Behavior: I do see "Disposing TestClass" being printed after the using statement as expected but I also expect "TestClass Finalizer called" to be printed after the GC commands I run. I ensured that I skip calling GC.SuppressFinalize(this); in the Dispose method. Looks like disposed variables don't get finalized even after they are out-of-scope. They seem to get finalized just before the program exits.
Actual Behavior: I only see "Disposing TestClass" being printed after the using statement as expected only don't see "TestClass Finalizer called" after the GC commands. I only see it just before the program exits.
Isn't this considered a memory leak?
If I convert this to a non-disposable class and update the code like below, I do see the finalizer being called after the GC commands.
TestClass test = new TestClass();
test = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
public class TestClass
{
~TestClass()
{
Console.WriteLine("TestClass Finalizer called");
}
}