C#内存占用释放

序言

系统启动起来以后,内存占用越来越大,使用析构函数、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);
    }
}
View Code

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 
View Code

资料

https://blog.csdn.net/bdstjk/article/details/8482711

猜你喜欢

转载自www.cnblogs.com/cnki/p/11876909.html