How to find out in which generation of Garbage Telescope an object is allocated?

Asked

Viewed 66 times

3

Considering my previous question on the generations of the CG, would like to understand if considering the "moment" through which an object is passing within its life cycle, brings some benefit or is necessary to solve some kind of problem?

So that I program correctly, need to know the generation in which an object is allocated?

  • You mean where he is in memory? I never needed to know that until today.

  • @Paulohdsousa No, I refer to the "generations" of the GC. Perhaps the question becomes clearer if you take this my other question.

1 answer

4


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

The practical usefulness in normal code is debatable. You can’t even make much use of it because it’s implementation detail. It is useful for making diagnostics, measurements, experiments and perhaps something very advanced, probably a development tool more than a normal application.

What you need to know is that the ideal is that objects die young or live forever, you don’t need to know what generation he’s in. When we say you must prevent an object from reaching Gen2, it doesn’t mean you have to keep monitoring it. The problem with Gen2 is that if it has to be collected it can take a very long pause.

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)}");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.