#735 – Don’t Trust WeakReference.IsAlive If It Returns true

The WeakReference.IsAlive method can tell you if a particular object is still alive, i.e. it has not yet been garbage collected.  However, when IsAlive returns true, you can’t then necessarily interact with the object through its weak reference, because it could be garbage collected before you get a chance to use it.

For example:

            WeakReference dogRef = new WeakReference(dog);

            // Later, try to ref original Dog

            if (dogRef.IsAlive)
            {
                // Oops - garbage collection on original Dog could occur here
                ((Dog)dogRef.Target).Bark();
            }

You can trust IsAlive when it returns false, since a garbage collected object is not in danger of being reconstituted.  But the correct pattern for checking to see if an object is still alive is:

            WeakReference dogRef = new WeakReference(dog);

            // Later, try to ref original Dog

            Dog origDog = (Dog)dogRef.Target;
            if (origDog != null)
            {
                origDog.Bark();
            }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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

w

Connecting to %s

%d bloggers like this: