序言
系统启动起来以后,内存占用越来越大,使用析构函数、GC.Collect什么的也不见效果,后来查了好久,找到了个办法,就是使用 SetProcessWorkingSetSize函数。这个函数是Windows API 函数。下面是使用的方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[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程序内存占用默认比较大,这个方法可以极大优化程序内存占用。 其实吧,百度了下,这个函数是将程序的物理内存尽可能转换为虚拟内存,大大增加硬盘读写,是不好的。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#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