[英]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.
想象一下,我有一个A类,现在,我想要计算GC收集A的对象的次数。
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. 我所说的是,可以在A类中保留一个名为count的静态字段,并在该对象的Finalize()调用中增加它。
The answer he was expecting was something called a static block. 他期待的答案就是所谓的静态块。 I've never heard of this in .NET/C#.
我在.NET / C#中从未听说过这个。 Can someone explain what's this static block?
有人可以解释一下这个静态块是什么吗?
使用memprofiler , Redgate Ants , dotTrace , CLR Profiler等工具 ( 显然需要.NET 3.5的管理员权限)或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#. 静态块实际上是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. 我能想到的唯一方法就是让你的类实现
IDisposable
,有一个名为disposeCount
的静态字段,并在每次调用Dispose
递增它,或者确保正如你在Finalize
方法中所说的那样。 Your answer was defintely not wrong, and you should point that out to them if you get a 2nd interview :) 你的答案绝对没有错,如果你第二次面试,你应该向他们指出:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.