The property WeakReference.IsAlive returns true when the target instance to which the WeakReference is pointing to is alive. While IsAlive retuns true there is no guarantee that the Target was not collected in the meantime, because the GC can run at any time between any instructions. The following code can run into a NullReferenceException.
if (_weaRef.IsAlive)
{
MyClass obj = (MyClass)_weaRef.Target;
var val = obj.ToString();
}
The correct usage pattern with the WeakReference should be as following:
// create a temporary reference to the target MyClass obj = _weaRef.Target as MyClass; // when not null then the target is alive if (obj != null) { var val = obj.ToString(); }
The MSDN documentation declares this problem in the Remarks section as following: “Because an object could potentially be reclaimed for garbage collection immediately after the IsAlive property returns true, using this property is not recommended unless you are testing only for a false return value.”
Update: I found this blog post from Chris Lvon in which he explains the problem in detail.


Classic TOCTOU (Time-of-Check/Time-of-Use), make sure to avoid stuff like that!
By: g$ on September 30, 2010
at 1:05 pm
Yes. Unfortunately there are many wrong examples out there in the web.
By: beatkiener on September 30, 2010
at 1:09 pm
Also, WeakReference.Target has defined NULL as a possible return value! You can NEVER NOT CHECK IT.
In addition to having TOCTOU, the first example is just not correct.
Moral of the story: if it CAN return NULL, you MUST check for it. No exceptions (pun very intentional)!
By: g$ on September 30, 2010
at 1:11 pm
Yes of course. But I’m already checking that with the use of the as-casting operator which returns null if the target is not of the excepted type or the Target is null. What is wrong with that?
By: beatkiener on September 30, 2010
at 1:16 pm
Nothing wrong with second example. I was refering to first example. I said “first example” in my follow-up, sorry you missed that.
By: g$ on September 30, 2010
at 2:20 pm
Yes, sorry. (I should not answer to blog entries when my brain tries to solve some wired project problems I’m currently working on…)
By: beatkiener on September 30, 2010
at 2:24 pm