#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();
            }

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

Leave a comment