Mono上奇怪的WeakReference行为

使用Mono 2.11.3(SGen)以及稳定的2.10.8版本,使用WeakReference的测试代码失败了。 在像这样的简单代码中

object obj = new object(); WeakReference wr = new WeakReference(obj); Assert.IsTrue(wr.IsAlive); obj = null; GC.Collect(); Assert.IsFalse(wr.IsAlive); 

第二个断言将失败。 添加GC.WaitForPendingFinalizers没有帮助。 这是Mono或我头脑中的错误吗? 谢谢

这不是一个错误,而是一个实现细节,其中Mono GC的行为与MS GC不同。 在这种情况下,由于您在同一堆栈帧中创建了对象obj,因此保守堆栈扫描代码恰好保持活动状态。 在实际代码中(与这样的琐碎测试案例相对),这不是问题。 如果对于您的特定情况,我建议在单独的方法中分配对象及其WeakReference:

 static WeakReference Alloc () { return new WeakReference (new object ()); } 
 [MethodImpl((MethodImplOptions.NoInlining)] static WeakReference Alloc () { return new WeakReference (new object ()); } 

编译时必须确保Alloc()方法不是内联的