随着 WPF 应用程序导航增加内存分配

Growing memory allocation as WPF application navigates

我正在构建一个 WPF 应用程序,并且一直在尝试实现在单击按钮时打开一个新页面。

该按钮位于 MainPage 页面中,它会打开 SafetySettings 页面。然后在 SafetySettings 页面中有一个按钮可以打开 MainPage。

我能够成功打开页面的唯一方法是:

    private void btnTest_Click(object sender, RoutedEventArgs e)
    {
        SafetySettings safety = new SafetySettings();
        this.Frame.Navigate(typeof(SafetySettings),safety);
    }

这按预期工作,但我注意到随着我在页面之间交换,程序的内存分配不断增加。我想我没有正确实现这一点,但我想不出另一种从当前页面打开新页面的方法。

MainPage.xaml.cs

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace DataAcquisitionGUI
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            SafetySettings safety = new SafetySettings();
            this.Frame.Content = null;
            this.Frame.Navigate(typeof(SafetySettings),safety);
        }
    }
}

您的内存分配正在增加,因为您每次单击按钮时都会创建新的 SafetySettings,而且我认为您没有正确处理该项目,因此没有清理。 在您的 SafetySettings 中实现 IDisposable 接口,或者创建一个 "destroys" 您的 class 实例的方法。这可以帮助您保持应用程序没有未使用的资源!