我已经完成了非常简单的测试,只是为了了解 wpf 如何处理内存。
我用一个窗口创建了一个项目,其中有一个 Button
。
第二个窗口完全是空的。
当我按下 Button
时点击打开第二个窗口
窗口 1 后面的代码:
/// <summary>
/// Interaction logic for WindowTest1.xaml
/// </summary>
public partial class WindowTest1 : Window
{
public WindowTest1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var wt2 = new WindowTest2();
wt2.ShowDialog();
wt2 = null;
}
}
xaml 窗口 1:
<Window x:Class="WpfAppXtesting.WindowTest1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfAppXtesting"
mc:Ignorable="d"
Title="WindowTest1" Height="450" Width="800">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Height="148" Margin="191,138,0,0" VerticalAlignment="Top" Width="267" Click="Button_Click"/>
</Grid>
window2 后面的代码:
/// <summary>
/// Interaction logic for WindowTest2.xaml
/// </summary>
public partial class WindowTest2 : Window
{
public WindowTest2()
{
InitializeComponent();
}
}
xaml 代码窗口 2:
<Window x:Class="WpfAppXtesting.WindowTest2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfAppXtesting"
mc:Ignorable="d"
Title="WindowTest2" Height="450" Width="800">
<Grid>
</Grid>
在下图中,我截取了内存状态的屏幕截图。 仅启动第一个窗口时我使用的第一行。 第二个窗口打开时的第二行。 第二个窗口关闭时的第三行。 我在十次后打开和关闭第二个窗口的最后一个列表。
为什么内存不回到第一个列表使用?
最佳答案
首先,您没有在关闭第二个窗口后调用 GC.Collect
强制立即进行垃圾回收,因此您不能假设该窗口已被回收你拍摄最后一张内存快照。
即使您明确调用了 GC.Collect
,您也不能假定 CLR 实际上会立即释放占用的内存。分配和释放内存在性能方面并不是免费的,并且由于应用程序稍后会请求更多内存的变化,因此没有必要立即将内存段释放回操作系统 (OS)。
.NET 应用程序在托管环境中执行,CLR 负责分配内存并将其释放回操作系统。它如何以及何时执行此操作是您无法在应用程序中真正控制的实现细节。
这里唯一需要关心的是关闭的窗口一旦关闭就应该有资格进行垃圾回收。它是。在 ShowDialog()
方法返回后将局部变量设置为 null
没有任何区别。
关于c# - WPF 每次打开和关闭窗口时增加内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50894863/