Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force WeakReference to die?

I wanted to do this in order to test my code. I suppose I could make another wrapper around the weakreference object, but would prefer to work directly to simulate the original object getting reclaimed.

This is the code that I have so far

 var myString = "someString";
 var myStringRef = new WeakReference(myString);
 myString = null;
 GC.Collect();
 Assert.IsFalse(myStringRef.IsAlive) //I want this to pass, but it failed. IsAlive is still true.

What can I do to force the last line above to not fail (ie. !IsAlive)

I have some framework logic that does housekeeping based on the status of the weakreference. I want to be able to test that logic, to do so, I need to be able to change the weakreference state at will - so how can I do this?

like image 906
Alwyn Avatar asked Mar 22 '23 16:03

Alwyn


2 Answers

I wonder if this has something to due with the fact that strings are interned, because the following test passes:

    var myObject = new object();
    var myObjectRef = new WeakReference(myObject);
    myObject = null;
    GC.Collect();
    Assert.IsFalse(myObjectRef.IsAlive);
like image 91
ken Avatar answered Apr 06 '23 18:04

ken


Instead of hardcoding the string into the source file, read it in via an external source. For example, you can create a TestStrings.txt file where your string(s) are placed and use this.

string myString = File.ReadAllText(@"TestStrings.txt");         

var myStringRef = new WeakReference(myString);
myString = null;

GC.Collect();
Assert.IsFalse(myStringRef.IsAlive);

This should return false. As mentioned in the other answer, this is indeed due to string interning.

By reading the text from an external source the strings won't be interned here which seems to be what you want for this test. (You can check if the string is interned by using String.IsInterned method).

like image 45
keyboardP Avatar answered Apr 06 '23 18:04

keyboardP