测试/验证弱引用

测试/验证弱引用

问题描述:

我想验证设置 WeakReference 不会意外地持有对被引用对象的强引用.(这是一个示例,说明如何很容易意外地做这个.)

I'd like to verify that code setting up a WeakReference does not accidentally hold a strong reference to the referenced object. (Here's an example of how it is easy to accidentally do this.)

这看起来是检查无意强引用的最佳方法吗?

Does this look like the best way to check for inadvertent strong references?

TestObject testObj = new TestObject();
WeakReference wr = new WeakReference(testObj);

// Verify that the WeakReference actually points to the intended object instance.
Assert.Equals(wr.Target, testObject);

// Force disposal of testObj;
testObj = null;
GC.Collect();
// If no strong references are left to the wr.Target, wr.IsAlive will return false.
Assert.False(wr.IsAlive);

我就此事与 Microsoft 取得了联系,并了解到/确认:

I got in touch with Microsoft about this and learned/confirmed that:

  • GC.Collect() 强制阻塞垃圾收集.
  • GC.Collect() 运行时,它不会神秘地跳过符合集合条件的对象.遵循可预测的规则来确定要收集哪些对象.只要您了解这些规则(即如何处理可终结对象),您就可以强制销毁特定对象,尽管被销毁对象使用的内存可能会或可能不会被释放.
  • GC.Collect() forces a blocking garbage collection.
  • When GC.Collect() runs, it won't mysteriously skip over collection-eligible objects. Predictable rules are followed for determining which objects to collect. As long as you operate with an understanding of those rules (i.e. how finalizable objects are handled), you can force a particular object to be destroyed though the memory used by the destroyed object may or may not be freed.

关于我的博客的更多信息:.Net 垃圾回收可以强制执行吗?

More information on my blog: Can .Net garbage collection be forced?