WPF 窗口关闭后不释放内存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14411154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A WPF window doesn't release the memory after closed
提问by Terry
I'm stilling trying to figure out the answer to this question: https://stackoverflow.com/questions/14379994/wpf-memory-optimization-advice
我仍在试图找出这个问题的答案:https: //stackoverflow.com/questions/14379994/wpf-memory-optimization-advice
So I created a test code:
所以我创建了一个测试代码:
private void Application_Startup_1(object sender, StartupEventArgs e)
{
ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
MainWindow window = new MainWindow();
window.Show();
window.Close();
window = null;
GC.Collect();
}
The MainWindow is a automatic created window by Visual Studio and I haven't add any code to it. Before the line "MainWindow window = new MainWindow();", the application occupies 4M memory. When the window is opened, it became 13M. It doesn't change even if we close the window and call the GC.Collect()
MainWindow 是 Visual Studio 自动创建的窗口,我没有向其中添加任何代码。在“MainWindow window = new MainWindow();”这一行之前,应用程序占用了4M内存。当窗口打开时,它变成了13M。即使我们关闭窗口并调用 GC.Collect() 它也不会改变
What are these extra memory being used for and how can we release them?
这些额外的内存是做什么用的,我们如何释放它们?
回答by Andrew Rondeau
Based on the answer at https://stackoverflow.com/a/4800489/1711103, you might need to explicitly set your Window's parent property. For example, in your constructor, you can call:
根据https://stackoverflow.com/a/4800489/1711103上的答案,您可能需要明确设置 Window 的父属性。例如,在您的构造函数中,您可以调用:
this.Parent = this;

