单声道奇怪行为的WeakReference [英] strange WeakReference behavior on Mono

查看:170
本文介绍了单声道奇怪行为的WeakReference的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是使用WeakReference的失败我使用单声道2.11.3(SGEN)以及稳定的2.10.8版本进行测试的代码。在一个简单的这样的代码

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于事无补。这是单声道或在我的脑海中的错误?
谢谢

the second assert will fail. Adding GC.WaitForPendingFinalizers doesn't help. Is this a bug in Mono or in my head? Thanks

推荐答案

这是不是一个错误,而是一个实现细节,其中单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 ());
}

这篇关于单声道奇怪行为的WeakReference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆