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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With