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;
 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?


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;


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

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;

Literal strings are interned by default, so despite the fact that you null myString the instance is still rooted by the intern table.

Please see my answer to this question for details about how interning is handled.

to do so, I need to be able to change the weakreference state at will

You could build an abstraction around WeakReference and make that testable (using an interface or a "test mode" which allows you to change the value returned by IsAlive).

Need Your Help

Get POST Values in ASP.NET using NameValueCollection forms post submit namevaluecollection

So I have 2 pages. They both have the same master page and are part of the same Web Application. I am trying to submit one page to the other. On the submitting page I have a few elements such as

What's the best way to remove HTML from a string?

regex coldfusion

I recently started using the following RegEx in a ReReplace() function to strip HTML tags from a string using ColdFusion. Please note: I am not using this as protection from XSS or SQL injection; t...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.