Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if in destructor I create an alive reference to an object?

Tags:

c#

.net

Situation:

  1. Object becomes eligible for GC
  2. GC starts collection
  3. GC calls destructor
  4. In destructor I, for example, add current object to static collection

In process of collection object becomes ineligible for GC, and will be eligible in future, but in specification said that Finalize can be called only once.

Questions:

  1. will object be destroyed?
  2. will finalize be called on next GC?
like image 578
Oleh Nechytailo Avatar asked Dec 30 '12 12:12

Oleh Nechytailo


1 Answers

The object will not be garbage collected - but next time it's eligible for garbage collection, the finalizer won't be run again, unless you call GC.ReRegisterForFinalize.

Sample code:

using System;

class Test
{
    static Test test;

    private int count = 0;

    ~Test()
    {
        count++;
        Console.WriteLine("Finalizer count: {0}", count);
        if (count == 1)
        {
            GC.ReRegisterForFinalize(this);
        }
        test = this;
    }

    static void Main()
    {
        new Test();
        Console.WriteLine("First collection...");
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("Second collection (nothing to collect)");
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Test.test = null;
        Console.WriteLine("Third collection (cleared static variable)");
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Test.test = null;
        Console.WriteLine("Fourth collection (no more finalization...)");
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

Output:

First collection...
Finalizer count: 1
Second collection (nothing to collect)
Third collection (cleared static variable)
Finalizer count: 2
Fourth collection (no more finalization...)
like image 171
Jon Skeet Avatar answered Oct 18 '22 14:10

Jon Skeet