WeakReference的错误? [英] WeakReference Bug?

查看:136
本文介绍了WeakReference的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[TestMethod]
public void Memory()
{
    var wr = new WeakReference("aaabbb");
    Assert.IsTrue(wr.IsAlive);
    GC.Collect();
    GC.Collect();
    GC.Collect();
    GC.Collect();
    GC.Collect();
    Assert.IsFalse(wr.IsAlive); //<-- fails here
}

这是.NET 3.5 SP1
可为什么这个测试失败,任何人都可以告诉我吗?

It's .NET 3.5 SP1
Can anyone can tell me why this test fails?

修改:感谢stusmith

Edit: Thanks stusmith

您有一个引用的字符串,   其中,因为它是一个常数,是   大概拘留(即不是动态   分配),并且绝不会   收集的。

You have a reference to a string, which since it is a constant, is probably interned (ie not dynamically allocated), and will never be collected.

这是它。更改第一行

var wr = new WeakReference(new object());

和测试通过: - )

推荐答案

我能想到把我的头顶部的两个可能的原因:

I can think of two possible reasons off the top of my head:

  1. 您正在运行调试。在调试参考持续更长的时间比释放,并可能超过你的想象。
  2. 您有一个引用字符串,因为它是一个常数,可能是拘留(即不是动态分配),而且永远不会被收集。

这篇关于WeakReference的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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