WeakReference的错误?错误、WeakReference

2023-09-04 00:44:59 作者:[好菇凉爸妈造]

[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:

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