Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 852
SeeR Avatar asked Oct 16 '08 12:10

SeeR


1 Answers

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.
like image 87
stusmith Avatar answered Oct 15 '22 10:10

stusmith