【问题标题】:Will this ChildWindow be collected by GC?这个 ChildWindow 会被 GC 收集吗?
【发布时间】:2012-02-08 17:34:55
【问题描述】:

最近我一直在使用匿名方法,所以我想知道我是否喜欢:

在我的 MainWindow 类中说,我有:

ChildWindow myChildWindow = new ChildWindow();
myChildWindow.Closing+= (o, e) => {
 //DoSomething
 rootGrid.Children.Remove(o as ChildWindow);
}
this.rootGrid.Children.Add(myChildWindow );
myChildWindow.Show();

在这种情况下,我将无法从 .Closing 中删除事件处理程序,因为它是使用匿名方法定义的。

这个 ChildWindow 还会被 GC 收集吗?

【问题讨论】:

    标签: c# wpf garbage-collection


    【解决方案1】:

    是的。

    您所做的只是创建一个带有闭包对象的委托并从子窗口引用它。

    您没有创建任何其他子窗口的引用。

    【讨论】:

    • 你的意思是闭包对象是ChildWindow类中的一个对象吗?喜欢public ClosingHandler Closing?因此,如果我的 MainWindow 类仍然具有对 ChildWindow ChildWindow anotherReferece = myChildWindow 的对象引用,那么额外的引用将不会被 GC 收集?
    • 查看my blog post 了解更多关于闭包的信息。这里不用担心 GC。
    猜你喜欢
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多