序言
系統啟動起來以后,內存占用越來越大,使用析構函數、GC.Collect什么的也不見效果,后來查了好久,找到了個辦法,就是使用 SetProcessWorkingSetSize函數。這個函數是Windows API 函數。下面是使用的方法:

[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Ansi, SetLastError = true)] private static extern int SetProcessWorkingSetSize(IntPtr process, int minimumWorkingSetSize, int maximumWorkingSetSize); public void Dispose() { GC.Collect(); GC.SuppressFinalize(this); if (Environment.OSVersion.Platform == PlatformID.Win32NT) { SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1); } }
C# 出來的Winform程序內存占用默認比較大,這個方法可以極大優化程序內存占用。 其實吧,百度了下,這個函數是將程序的物理內存盡可能轉換為虛擬內存,大大增加硬盤讀寫,是不好的。

#region 內存回收 [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")] public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize); /// <summary> /// 釋放內存 /// </summary> public static void ClearMemory() { GC.Collect(); GC.WaitForPendingFinalizers(); if (Environment.OSVersion.Platform == PlatformID.Win32NT) { SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1); } } #endregion
Winform如何降低系統內存
使用性能測試工具dotTrace 3.0,它能夠計算出你程序中那些代碼占用內存較多
資料
https://blog.csdn.net/bdstjk/article/details/8482711