弱引用的线程安全

发布于 2024-08-09 18:21:21 字数 245 浏览 5 评论 0原文

使用 Wea​​kReference 时,我们如何确定在 .IsAlive 和 .Target 调用之间没有收集目标?

例如:

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

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();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

々眼睛长脚气 2024-08-16 18:21:21

只需获取 Target 并检查它是否不为空:

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

IsAlive 的文档特别指出:

因为一个对象可能是
回收用于垃圾收集
紧接在 IsAlive 属性之后
返回true,使用这个属性是
除非您正在测试,否则不推荐
仅用于错误返回值。

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.

土豪我们做朋友吧 2024-08-16 18:21:21

“IsAlive”属性的唯一目的是用于以下情况:如果 WeakReference 的目标已被销毁,您希望采取一些操作,但又不想冒意外使其存活时间超过必要时间的风险。例如,如果

  if (someWeakReference.Target == null)
    cleanup_related_object();

垃圾收集器(无论出于何种原因)在评估 someWeakReference.Target 的代码之后立即触发,GC 就会注意到存在对该对象的强引用并阻止其收集。另一方面,说:

  if (!someWeakReference.IsAlive)
    cleanup_related_object();

不会有意外延长 someWeakReference 目标的目标生命周期的风险

The only purpose of the "IsAlive" property is for situations where you want to take some action if the target of a WeakReference has already been destroyed, but where you don't want to risk accidentally keeping it alive longer than necessary. If one were to say, e.g.

  if (someWeakReference.Target == null)
    cleanup_related_object();

and the garbage-collector were to (for whatever reason) trigger right after the code that evaluated someWeakReference.Target, the GC would notice that there existed a strong reference to that object and preclude its collection. On the other hand, saying:

  if (!someWeakReference.IsAlive)
    cleanup_related_object();

there would be no risk of accidentally prolonging the lifetime of the target of someWeakReference target

原谅过去的我 2024-08-16 18:21:21

你不能。将 myWeakReference.Target 分配给变量,并检查是否为 null。

You can't. Assign myWeakReference.Target to a variable, and check for null.

近箐 2024-08-16 18:21:21

你可以摆脱 if :)

(myWeakReference?.Target as MyType)?.Foo()

you can get rid of the if :)

(myWeakReference?.Target as MyType)?.Foo()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文