基於.NET Framework 的Windows應用程式如何回收記憶體

來源:互聯網
上載者:User
        基於.NET Framework 的Windows應用程式,你會發現你對程式的操作越多,
佔用的記憶體會不斷向上飆升,即使你結束了長時間啟動並執行操作.這種情況對於一個非常小的應用都是這樣.
這種情況一般並不是.Net 記憶體泄露,而是因為.Net沒有即時回收你分配的記憶體。下面是從一個朋友那兒搞到的一段代碼,
它能夠協助你即時回收記憶體.

public class RevokeMemory
    {
        public static void ReduceMemoryFootPrint()
        {
            int currentMinWorkingSetValue = 0;
            int currentMaxWorkingSetValue = 0;
            Process currentProcess = Process.GetCurrentProcess();

            try
            {
                if(GetProcessWorkingSetSize(currentProcess.Handle, out currentMinWorkingSetValue, out currentMaxWorkingSetValue))
                {
                    currentProcess.MinWorkingSet = (IntPtr)currentMinWorkingSetValue;
                }
            }
            catch(Exception err)
            {
                string additionalInfo = "MinWorkingSet value is set to: " + currentMinWorkingSetValue.ToString();
                additionalInfo += " Process In Error: " + currentProcess.ProcessName;
                //Log error message
            }
        }

        [DllImport("kernel32.dll")]
        public static extern bool GetProcessWorkingSetSize( IntPtr proc, out int min, out int max );

        [DllImport("kernel32.dll")]
        public static extern bool SetProcessWorkingSetSize( IntPtr proc, int min, int max );

    }

調用的時機:
1. 主介面上做一個計時器,每間隔一定的時間進行調用,但鄙人認為這種效果並不好。在你進行長時間啟動並執行操作之前。需要禁止它。
2.每完成一個大的操作或者比較消耗記憶體的操作之後,調用。
本人做了一個測試,以前幾時兆的記憶體飆升,現在總的消耗的記憶體都在幾兆到30兆之間了.
不信你可以試一試.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.