Counting number of GC cleanups on an object
How do I keep a count of the number of times that objects of a specific class (type?) are getting disposed in the lifetime of my application. Imagine I have a class A, now, I want to count how many times the objects of A get collected by the GC.
I hope I am phrasing this right because I was asked开发者_运维知识库 this in an interview today and the answer I gave did not satisfy the interviewer. And this is what I imagine he was trying to ask.
What I said was that one could keep a static field called count in the class A and increment it in the Finalize() call of that object.
The answer he was expecting was something called a static block. I've never heard of this in .NET/C#. Can someone explain what's this static block?
Use a tool like memprofiler, Redgate Ants, dotTrace, CLR Profiler (needs admin rights for .NET 3.5 apparently) or the team edition of Visual Studio.
Maybe he was referring to a static constructor for the class?
public class Foo {
public static Foo() { /* gets called once before first operator new */ }
}
A static block is really another name for a Static Constructor in C#. It is called automatically to intialize a class before the first instance is created. I can't see how this will help you keep track of how many times a class is disposed though. Only way I could think of would be to have your class implement IDisposable
, have a static field called disposeCount
and increment it on every call to Dispose
or to be sure as you rightly said in the Finalize
method. Your answer was defintely not wrong, and you should point that out to them if you get a 2nd interview :)
精彩评论