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

Winform如何降低系統內存

使用性能測試工具dotTrace 3.0,它能夠計算出你程序中那些代碼占用內存較多

資料

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

https://blog.csdn.net/yyws2039725/article/details/85480263

NET資源泄露與處理方案


免責聲明!

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



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