Generation of GC after resurrection?

Suppose the object has a Finalize() method.

When it is created first, a pointer is added to the finalization queue.

The object has no links.

When garbage collection occurs, it moves the link from the finalization queue to the f-reachable queue, and the thread starts to run the Finalize method (sequentially after the methods of other Finalize objects).

So, now the object (after resurrection) has only one root, which is a pointer from the queue available to f.

At the moment, is the object added to the next generation?

+6
source share
2 answers

This is something you can try. Run this code in the Release assembly without an attached debugger:

 using System; class Program { static void Main(string[] args) { var obj = new Foo(); // There are 3 generations, could have used GC.MaxGeneration for (int ix = 0; ix < 3; ++ix) { GC.Collect(); GC.WaitForPendingFinalizers(); } Console.ReadLine(); } } class Foo { int attempt = 0; ~Foo() { // Don't try to do this over and over again, rough at program exit if (attempt++ < 3) { GC.ReRegisterForFinalize(this); Console.WriteLine(GC.GetGeneration(this)); } } } 

Conclusion:

1
2
2

Thus, he remains in the generation to which he was moved by the collection, moving on to the next in each collection until he gets to the last. Which makes sense at all.

+3
source

The answer seems to be yes, it will happen. http://msdn.microsoft.com/en-us/magazine/bb985010.aspx says:

... To recover the memory used by objects requiring refinement, two GCs are required. In fact, more than two collections may be required, as objects can be passed on to the older generation.

+1
source

All Articles