strange WeakReference behavior on Mono(Mono 上奇怪的弱引用行为)
问题描述
使用 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 上奇怪的弱引用行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mono 上奇怪的弱引用行为


- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01