当我设置 WPF 子窗口的 Owner 属性时,是否会阻止它被垃圾收集?
如果父窗口 A 将对其自身的引用传递给子窗口 B(通过构造函数),以便 B 可以将其 Owner 属性设置为 A,这是否意味着子窗口 B 不会被垃圾回收,因为父窗口 A 在以下时间内保持活动状态:应用程序?
如果是这种情况,在 WPF 窗口之间创建干净的父/子关系的最佳方法是什么?这种类型的关系有弱引用的概念吗?
更新:大脑失败。好吧,我不应该这么晚才问这个问题。我把问题过于复杂化了。我的大脑颠倒了 GC 的逻辑,认为子进程无法收集,因为它引用了其他完全错误的东西。无论如何,感谢所有回答的人。
If parent window A passes a reference to itself to child window B (via constructor) so that B can set its Owner property to A, does that mean child window B won't be garbage collected because parent window A stays alive for the duration of the application?
If this is the case, what is the best approach for creating clean parent/child relationships between WPF windows? Is there a concept of weak references for this type of relationship?
UPDATE: Brain FAIL. Okay, I shouldn't have asked this question so late in the afternoon. I was over-complicating the problem. My brain reversed the logic of the GC and was thinking the child couldn't collect because it referenced something else which is totally false. Thanks to all who answered anyway.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我创建了您提到的 Windows,并添加了一些代码:
一旦关闭 B 并按下第二个按钮,析构函数就会运行。希望这能回答这个问题。
I created the Windows you mention, and added some code:
Once B had been closed and the second button pressed, the destructor ran. Hopefully this answers the question.
只要堆栈中不存在对对象的引用,对象就可以进行垃圾回收。因此,只要您在
window A
中保留对window B
的引用,那么它就永远不会被垃圾回收。为了使其符合 GC 的条件,您必须显式地将对其的任何引用设置为 null 或另一个对象引用。
Objects are eligible for garbage collection as soon as no references to them exist in the stack. For this reason as long as you hold a reference to
window B
withinwindow A
then it will never be garbage collected.In order to make it eligible for GC you'll have to explicitly set any reference to it to null or another object reference.
正确,子窗口 B 一直存在到父窗口 A 存在为止,因为存在从父窗口到 WindowB 的实时引用。
当 WindowB 关闭时,清除父窗口对窗口 B 的引用。这样,就没有对 WindowB 的实时引用,并且它有资格进行垃圾收集。
另一件事是,在所有 Disposable 对象超出范围之前调用 Dispose 方法是一种很好的做法。您可以对本地/一次性对象使用
using
语句。Correct, child window B lives until parent Window A lives, because there is a live reference from Parent window to WindowB.
Clear the Parent window reference to Window B when the WindowB close. In this way, there is no live reference to WindowB and it's eligible to garbage collected.
One more thing, it's a good practice to call the Dispose method for all the Disposable objects before they go out of scope. You can use
using
statement for local/disposable objects.