How to find out in what generation of garbage collector an object is allocated?

3

Considering my previous question or in> is it necessary to solve some kind of problem?

In order for me to program correctly , do I need to know the generation in which an object is allocated?

    
asked by anonymous 27.04.2017 / 20:25

1 answer

4

Yes, it is possible with the method GC.GetGeneration() . .

Practical utility in normal codes is debatable. You can not even use that much because it's implementation detail. It is useful for making diagnostics, measurements, experiments and perhaps something very advanced, probably a development tool rather than a normal application.

What you need to know is that the ideal is that objects die young or live forever, you do not need to know in what generation it is. When we say we should prevent an object from reaching Gen2, it does not mean that you need to be monitoring that. The problem with Gen2 is that if it has to be collected it may take a very long break.

using System;

public class Program {
    public static void Main() {
        var objeto = new object();
        Console.WriteLine($"Geração {GC.GetGeneration(objeto)}");
        GC.Collect();
        Console.WriteLine($"Geração {GC.GetGeneration(objeto)}");
        GC.Collect();
        Console.WriteLine($"Geração {GC.GetGeneration(objeto)}");
    }
}

See working on .NET Fiddle . Also I put it in GitHub for future reference .

    
27.04.2017 / 21:28