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); } }