首页 > 解决方案 > 为什么我的 WPF 应用程序没有释放它的内存?

问题描述

我不明白为什么我的测试 WPF 应用程序在我关闭 MainWindow 并将其设置为 null 甚至运行垃圾收集器后没有释放它使用的内存?

一开始,甚至在创建 MainWindow 之前,应用程序几乎不占用内存,大约 5 MB,但是当我创建第一个窗口时,它占用了 43 MB,并且在应用程序的剩余生命周期中一直存在。难道不重新启动应用程序就可以再次将其恢复到 5 MB 吗?

诊断工具

public App()
{
    ShutdownMode = ShutdownMode.OnExplicitShutdown;

    DispatcherTimer dispatcherTimer = new DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0, 0, 2);

    Thread.Sleep(2000);
    dispatcherTimer.Start();
}

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    if (MainWindow == null)
    {
        MainWindow = new MainWindow();
        MainWindow.Show();
    }
    else
    {
        MainWindow.Close();
        MainWindow = null;

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }
}

标签: c#wpfmemory

解决方案


您有内存泄漏,因此GC将无法收集您的MainWindow. 您必须取消订阅您的事件处理程序。因此,将计时器保留在支持字段中:

MainWindow = null;
// Add this:
this.dispatcherTimer.Tick -= new EventHandler(dispatcherTimer_Tick);
this.dispatcherTimer.Stop();

推荐阅读