弱引用的线程安全 [英] Thread Safety of WeakReference

查看:109
本文介绍了弱引用的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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.

这篇关于弱引用的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆