I have a test that I expected to pass but the behavior of the Garbage Collector is not as I presumed:
[Test]
public void WeakReferenceTest2()
{
var obj = new object();
var wRef = new WeakReference(obj);
wRef.IsAlive.Should().BeTrue(); //passes
GC.Collect();
wRef.IsAlive.Should().BeTrue(); //passes
obj = null;
GC.Collect();
wRef.IsAlive.Should().BeFalse(); //fails
}
In this example the obj
object should be GC'd and therefore I would expect the WeakReference.IsAlive
property to return false
.
It seems that because the obj
variable was declared in the same scope as the GC.Collect
it is not being collected. If I move the obj declaration and initialization outside of the method the test passes.
Does anyone have any technical reference documentation or explanation for this behavior?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…