Posted by: beatkiener | February 16, 2010

Be careful when using WeakReference.IsAlive

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.

Advertisement

Responses

  1. Classic TOCTOU (Time-of-Check/Time-of-Use), make sure to avoid stuff like that!

    • Yes. Unfortunately there are many wrong examples out there in the web. :)

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

  3. 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?

    • Nothing wrong with second example. I was refering to first example. I said “first example” in my follow-up, sorry you missed that.

  4. Yes, sorry. (I should not answer to blog entries when my brain tries to solve some wired project problems I’m currently working on…) :)


Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.