Partilhar via


Multiple calls to GC.ReRegisterForFinalize

Holi Celebration at our appartment complex

What happens when there are multiple calls to GC.ReRegisterForFinalize for the same object?

Consider the following C# code

 class MyClass
{
    ~MyClass()
    {
        Console.WriteLine("~MyClass");
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass mc = new MyClass();
        GC.ReRegisterForFinalize(mc); // 1
        GC.ReRegisterForFinalize(mc); // 2
        GC.ReRegisterForFinalize(mc); // 3

        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

Here for the same object we have called GC.ReRegisterForFinalize thrice.

This is one of the few cases where the behavior of .NET and .NET Compact Framework differs.

In case of .NET the MyClass finalizer is called 4 times. Since the object has a finalizer, it is anyway finalized once and for the additional 3 calls to re-register it is finalized 3 more times.

In case of .NET Compact Framework the finalizer is called only once. The reason being internally finalizable is just a bool flag. Each time GC.SuppressFinalize is called it is set to false and each time GC.ReRegisterForFinalize is called it is set to true. So multiple calls doesn’t have any effect.

Hopefully this is one piece of information which none of my readers ever find useful, but since I got a bug assigned for the difference in behavior I might as well let folks know.