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?
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);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With