gpt4 book ai didi

c# - 弱引用的线程安全

转载 作者:可可西里 更新时间:2023-11-01 03:14:38 25 4
gpt4 key购买 nike

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

例如:

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

最佳答案

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

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

docs for IsAlive具体来说:

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.

关于c# - 弱引用的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1687045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com