wpf 内存减少使用 GC回收

代码

App.xaml.cs

    protected override void OnStartup(StartupEventArgs e)
    {    
//新增内存回收
this.MemoryHelper();
}

 

  private void MemoryHelper(int second = 30)
  {
      Thread t = new Thread(() =>
      {
          while (true)
          {
              try
              {
                  FlushMemory();
                  Thread.Sleep(TimeSpan.FromSeconds(second));
              }
              catch (Exception)
              {
              }
          }
      });
      t.Start();
  }

  [DllImport("kernel32.dll")]
  private static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);

  private void FlushMemory()
  {
      GC.Collect();
      GC.WaitForPendingFinalizers();
      if (Environment.OSVersion.Platform == PlatformID.Win32NT)
      {
          SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
      }
  }

 

 效果:

 

posted @ 2024-01-19 16:57  JohnnyLei  阅读(206)  评论(0)    收藏  举报