C# winform在關閉窗體的時候及時釋放內存問題


winform中如果每次打開的窗體都是通過new出來的,發現幾次過后就會出現提示”內存不足“問題,那么在關閉窗體的時候怎么處理可以及時釋放內存?dispose方法可能也無法解決這個問題。我們可以每次在關閉窗體的時候刷新存儲器來徹底釋放內存。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

[DllImport("kernel32.dll")]
private static extern bool SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
//關閉窗體按鈕 
private void btnReturn_Click(object sender, EventArgs e)
{
  this.Close();
  FlushMemory();
}
//刷新存儲器
private static void FlushMemory()
{
  GC.Collect();
  GC.WaitForPendingFinalizers();
  if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  {
    SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
  } 
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM