测试/validationWeakReference

我想validation设置WeakReference代码是否意外地保存了对引用对象的强引用。 (这是一个很容易意外地做到这一点的例子。)

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

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

我与微软就这一点取得了联系,并了解到/确认:

  • GC.Collect()强制阻塞垃圾回收。
  • GC.Collect()运行时,它不会神秘地跳过符合条件的集合对象。 遵循可预测的规则来确定要收集的对象。 只要您了解这些规则(即如何处理最终化的对象),您就可以强制销毁特定对象,尽管被破坏对象使用的内存可能会被释放,也可能不被释放。

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

我昨天做到了这一点。 这是我必须添加的内容,以确保在上一次断言之前发生了收集:

  GC.Collect(); GC.WaitForPendingFinalizers(); GC.WaitForFullGCComplete(); GC.Collect(); 

如果在此之后.IsAlive仍然是真的,那么很可能在某处仍然存在强烈的引用。

顺便说一句 – 当您访问WeakReference目标时,请务必不要检查.IsAlive。 为了避免检查.IsAlive和.Target之间的竞争条件,请执行以下操作:

 var r = weakRef.Target AS Something; if (r != null) { ... do your thing }