Search code examples
c#.netweak-references

Thread Safety of WeakReference


When using a WeakReference, how can we be sure than the target is not collected between the .IsAlive and .Target calls?

For example:

if (myWeakReference.IsAlive)
{
    // How can we be sure the object is still alive while here?
    ((MyType)myWeakReference.Target).Foo();
}

Solution

  • Just get the Target and check whether it's not null:

    object target = myWeakReference.Target;
    if (target != null)
    {        
        ((MyType)target).Foo();
    }
    

    The docs for IsAlive specifically say:

    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.