c# - 为什么我的 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();
}
}
解决方案
您有内存泄漏,因此GC
将无法收集您的MainWindow
. 您必须取消订阅您的事件处理程序。因此,将计时器保留在支持字段中:
MainWindow = null;
// Add this:
this.dispatcherTimer.Tick -= new EventHandler(dispatcherTimer_Tick);
this.dispatcherTimer.Stop();
推荐阅读
- javascript - 将参数传递到 URL
- java - Java:ImageIcon - 图像文件更新,但 Java 框架中的图像图标没有
- android - 步进器内的日期选择器
- laravel - 通过回答安全问题手动重置密码而不发送电子邮件 - Laravel/auth
- r - 如何在ggplot lineplot中为具有相似颜色的多个子类着色?
- date - Applescript:通过添加具有奇怪行为的天数来增加月份
- c# - 使用 SQL Server CE 数据库部署 .exe 时遇到问题
- json - 如何在命令行上打印 JSON,但允许无效的 JSON 对象通过?
- python - python:在熊猫数据框中排列
- swift - 在 MacOS 中使用 NSSharingServicePicker 的 SwiftUI