SeeR
SeeR

Reputation: 2168

WeakReference Bug?

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

Upvotes: 5

Views: 781

Answers (1)

stusmith
stusmith

Reputation: 14103

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.

Upvotes: 16

Related Questions