WeakReference Bug?

2019-02-18 09:22发布

问题:

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

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

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.

That was it. Changed first line to

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

and the test passes :-)

回答1:

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

  1. You're running in debug. References in debug last longer than in release, and possibly longer than you might think.
  2. 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.