Weak References

suggest change

Weak references are… references, to other objects (aka “targets”), but “weak” as they do not prevent those objects from being garbage-collected. In other words, weak references do not count when the Garbage Collector evaluates objects as “live” or “dead”.

The following code:

var weak = new WeakReference<FinalizableObject>(new FinalizableObject());
GC.Collect();
GC.WaitForPendingFinalizers();

Produces the output:

<namespace>.FinalizableObject initialized
<namespace>.FinalizableObject finalized

FinalizableObject is a type whose constructor and finalizer write those two lines. GC.Collect does not run finalizers until GC.WaitForPendingFinalizers. A finalizer is still not guaranteed. The object can be collected even though the WeakReference<T> variable is still in scope.

Consequence #1: at any time, it is unsafe to assume whether a WeakReference target is still allocated on the managed heap or not.

Consequence #2: whenever a program needs the target of a WeakReference, it must handle both cases: the target is still alive, or it is not. TryGetTarget is the method that does that:

var target = new object(); // Any object will do as target
var weak = new WeakReference<object>(target); // Create weak reference
target = null; // Drop strong reference to the target

// ... Many things may happen in-between

// Check whether the target is still available
if(weak.TryGetTarget(out target))
{
    // Use re-initialized target variable
    // To do whatever the target is needed for
}
else
{
    // Do something when there is no more target object
    // The target variable value should not be used here
}

WeakReference<T> was added in .NET Framework 4.5. Every Framework version also has a non-generic WeakReference. The object can be collected between the IsAlive check and the read of Target, so prefer TryGetTarget.

var target = new object(); // Any object will do as target
var weak = new WeakReference(target); // Create weak reference
target = null; // Drop strong reference to the target

// ... Many things may happen in-between

// Check whether the target is still available
if (weak.IsAlive)
{
    target = weak.Target;

    // Use re-initialized target variable
    // To do whatever the target is needed for
}
else
{
    // Do something when there is no more target object
    // The target variable value should not be used here
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents