找一个对象活动引用找一个、对象

2023-09-04 00:35:44 作者:等我变成光

我要寻找一个托管/非托管API,让我找到哪些对象引用另一个对象,并有可能被垃圾收集,保留它。

I am looking for a managed/unmanaged API that will allow me to find which objects reference another object and are potentially keeping it from being garbage collected.

这样的API可能是这样的:

Such an API might look like this:

var foo = new Foo();
var bar = new Bar();
bar.Foo = foo;

var references = GC.GetReferencesTo(foo);
// references is an array that contains bar

我知道廓线仪,可用于这一点,但我想使它成为一个单元测试的一部分。是否有我可以使用托管或非托管API?

I know profilers can be used for this but I'd like to make it part of a unit test. Is there a managed or unmanaged API that I could use?

推荐答案

在非托管的DLL SOS(儿子的打击)提供了实现这一目标的手段,虽然我不相信它有显著的脚本支持,也没有提供一个简单的是指通过一个命令来实现这一目标。你将不得不反思变量的地址,检查所有gcroots的变量(包括堆栈明显),并处理其余部分。

The unmanaged dll SOS (Son Of Strike) provides a means to achieve this, though I do not believe it has significant scripting support, nor does it provide a simple means to achieve this via a single command. You would have to introspect the variable's address, check all gcroots for the variable (which would include the stack obviously) and deal with the remainder.

我会建议,如果你想证明一个对象的不可以引用,一个简单的方法是将(暂时)使finalizeable,确保其不再在堆栈上引用单元测试,然后通过 GC.Collect的强制几个垃圾收集() 然后使用 GC.WaitForPendingFinalizers() 。

I would suggest that, if you wish to prove that an object is not referenced, a simpler technique would be to (temporarily) make it finalizeable, ensure it is no longer referenced on the stack of your unit test and then force several garbage collections via GC.Collect() then use GC.WaitForPendingFinalizers().

您finalize方法可以设置一个静态布尔标志,然后你的单元测试可以断言这是真的。

Your finalize method can set a static boolean flag and then your unit test can assert this is true.

我会质疑的这一点没有进一步解释的效用的,但这很可能是最简单的证明在单元测试中不存在悬挂引用的方法

I would question the utility of this without further explanation but this is likely to be the simplest method of proving no dangling references exist in a unit test.