问题描述
使用 Mono 2.11.3 (SGen) 以及稳定的 2.10.8 版本对我来说使用 WeakReference 的测试代码失败了.在这样的简单代码中
Testing code that uses WeakReference failed for me using Mono 2.11.3 (SGen) as well as the stable 2.10.8 version. In a simple code like this
object obj = new object();
WeakReference wr = new WeakReference(obj);
Assert.IsTrue(wr.IsAlive);
obj = null;
GC.Collect();
Assert.IsFalse(wr.IsAlive);
第二个断言将失败.添加 GC.WaitForPendingFinalizers 没有帮助.这是 Mono 中的错误还是我脑海中的错误?谢谢
the second assert will fail. Adding GC.WaitForPendingFinalizers doesn't help. Is this a bug in Mono or in my head? Thanks
推荐答案
这不是一个错误,而是 Mono GC 与 MS GC 行为不同的实现细节.在这种情况下,由于您在同一个堆栈帧中创建了对象 obj,因此它恰好被保守的堆栈扫描代码保持活动状态.在实际代码中(与这样的琐碎测试用例相反),这不是问题.如果是针对您的特定情况,我建议在单独的方法中分配对象及其 WeakReference:
It is not a bug, but an implementation detail where the Mono GC behaves differently from the MS GC. In this case, since you created the object obj in the same stack frame, it happens to be kept alive by the conservative stack scanning code. In real code (as opposed to trivial test cases like this) this is not a problem. If for your particular case it is, I suggest allocating the object and its WeakReference in a separate method:
static WeakReference Alloc ()
{
return new WeakReference (new object ());
}
这篇关于Mono 上奇怪的弱引用行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!