Mono 上奇怪的弱引用行为

strange WeakReference behavior on Mono(Mono 上奇怪的弱引用行为)
本文介绍了Mono 上奇怪的弱引用行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Mono 2.11.3 (SGen) 以及稳定的 2.10.8 版本对我来说使用 Wea​​kReference 的测试代码失败了.在这样的简单代码中

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 上奇怪的弱引用行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)