Garbage collection of inaccessible objects in a loop

If I have a loop like this:

public class Foo {
     public Foo Foo;

     public Foo() {
     }
}

class Program {
    public static void Main(string[] args) {
         var foo = new Foo();
         long i = 0;
         while(i < Int64.MaxValue) {
             foo.Foo = new Foo();
             foo = foo.Foo;
             if(i % 10000 == 0)
                 GC.Collect();
             i++;
         }
         GC.Collect();
    }
}

The garbage collector will not clear the parent objects until the loop exits. Why is this? I see no way to refer to them from the code, as soon as fooreassigned, so shouldn't they be cleared?

I looked at the memory usage in the process in the task manager after passing some breakpoints that I set to determine if this was happening. It continues to rise inside the loop (up to several GB if I make it infinite), but it immediately flings when the loop completes and the second GC.Collect () is called.

+4
source share
1 answer

, :

class Foo
{
    public int Value;
    public Foo Next;

    public Foo(int value) { this.Value = value; Console.WriteLine("Created " + this.Value); }
    ~Foo() { Console.WriteLine("Finalized " + this.Value); }
}

class Program
{
    public static void Main(string[] args)
    {
        var foo = new Foo(0);
        for (int value = 1; value < 50; ++value)
        {
            foo.Next = new Foo(value);
            foo = foo.Next;
            if (value % 10 == 0)
            {
                Console.WriteLine("Collecting...");
                GC.Collect();
                Thread.Sleep(10);
            }
        }
        Console.WriteLine("Exiting");
    }
}

.NET 4.5, target x86, , : , "", Release OR x64 ( ), , :

Created 0
Created 1
Created 2
Created 3
Created 4
Created 5
Created 6
Created 7
Created 8
Created 9
Created 10
Collecting...
Finalized 9
Finalized 0
Finalized 8
Finalized 7
Finalized 6
Finalized 5
Finalized 4
Finalized 3
Finalized 2
Finalized 1
Created 11
Created 12
Created 13
...

? , CLR , : , JIT, , , re . ( , .) , x86/Debug , Foo(0) , ; . x86/Release x64 , - JIT , .

+6
source

Source: https://habr.com/ru/post/1544077/


All Articles