WeakReference 是否有冗余属性?

发布于 2024-08-08 14:39:22 字数 190 浏览 2 评论 0原文

.NET 中的 WeakReference 实现具有 IsAlive 属性。

1) 使用 IsAlive 属性或测试 Target 属性是否不为 null 之间是否存在性能/行为差异?

2) IsAlive 是一个多余的属性吗?

谢谢。

WeakReference implementation in .NET has an IsAlive Property.

1) Are there any performance/behavior differences between using the IsAlive property or testing whether the Target property is not null?

2) IsAlive is a redundant property?

Thanks.

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

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

发布评论

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

评论(3

如果没有你 2024-08-15 14:39:22

1) 不。在内部,IsAlive 执行的逻辑与检查目标几乎完全相同,并查看它是否为空。

2) 某种程度上,因为检查 ref.Target != null 是否与 ref.IsAlive 相当。然而,IsAlive 更具表现力,并且在维护代码时可能更容易理解。

1) No. Internally, IsAlive is doing almost exactly the same logic as checking target, and seeing if it's null.

2) Somewhat, since checking whether ref.Target != null is pretty much equivelent to ref.IsAlive. However, IsAlive is more expressive, and potentially easier to understand when maintaining the code.

苦行僧 2024-08-15 14:39:22

查看源代码,它们之间的行为没有区别。 obj.IsAliveobj.Target != null 更方便、更易读。

Looking at the source code, there is no difference in behavior between them. obj.IsAlive is simply more convenient and readable then obj.Target != null.

美人迟暮 2024-08-15 14:39:22

不难想象一个并发垃圾收集系统,其中即使是暂时持有对对象的引用,也很有可能导致该对象在下一次 GC 中幸存下来(在 .Net 下,这样做的可能性相对较小) )。在这样的系统下,使用对象的 Target 属性来确定它是否已死亡可能会产生恼人的副作用,即使对象的存活时间超过必要的时间。使用 IsAlive 属性可以避免这种风险。

请注意,IsAlive 只能可靠地用于确定对象是否已死亡。如果它报告某个对象还活着,则它可能会也可能不会获取其目标。

It is not hard to imagine a concurrent garbage-collection system in which holding a reference to an object even momentarily would have a substantial likelihood of causing that object to survive the next GC (under .Net, it has a relatively small likelihood of doing so). Under such a system, using an object's Target property to determine if it was dead could have the annoying side-effect of keeping the object alive longer than necessary. Using the IsAlive property would avoid that risk.

Note that IsAlive can only be used reliably to determine if an object is dead. If it reports that an object is alive, it may or may not be possible to acquire its target.

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