弱引用的线程安全
使用 WeakReference 时,我们如何确定在 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需获取
Target
并检查它是否不为空:IsAlive 的文档特别指出:
Just get the
Target
and check whether it's not null:The docs for
IsAlive
specifically say:“IsAlive”属性的唯一目的是用于以下情况:如果 WeakReference 的目标已被销毁,您希望采取一些操作,但又不想冒意外使其存活时间超过必要时间的风险。例如,如果
垃圾收集器(无论出于何种原因)在评估 someWeakReference.Target 的代码之后立即触发,GC 就会注意到存在对该对象的强引用并阻止其收集。另一方面,说:
不会有意外延长 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.
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:
there would be no risk of accidentally prolonging the lifetime of the target of someWeakReference target
你不能。将 myWeakReference.Target 分配给变量,并检查是否为 null。
You can't. Assign myWeakReference.Target to a variable, and check for null.
你可以摆脱 if :)
(myWeakReference?.Target as MyType)?.Foo()
you can get rid of the if :)
(myWeakReference?.Target as MyType)?.Foo()