弱引用的线程安全
问题描述:
使用WeakReference时,如何确定在.IsAlive和.Target调用之间未收集目标?
When using a WeakReference, how can we be sure than the target is not collected between the .IsAlive and .Target calls?
例如:
if (myWeakReference.IsAlive)
{
// How can we be sure the object is still alive while here?
((MyType)myWeakReference.Target).Foo();
}
答
只要获得 Target
并检查其是否不为空:
Just get the Target
and check whether it's not null:
object target = myWeakReference.Target;
if (target != null)
{
((MyType)target).Foo();
}
用于 IsAlive
的文档专门说:
The docs for IsAlive
specifically say:
因为可能会在IsAlive属性
返回true之后立即将对象
回收以进行垃圾回收
,因此使用此属性为$不建议使用b $ b,除非您仅测试
的返回值是虚假的。
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.