Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 940
Khash Avatar asked Nov 06 '09 11:11

Khash


1 Answers

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.

like image 78
Jon Skeet Avatar answered Sep 18 '22 00:09

Jon Skeet