.net中清理記憶體,清理佔用記憶體方式方法

來源:互聯網
上載者:User

標籤:

#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

 在系統中使用 SetProcessWorkingSetSize方法做了一個測試,調用該方法後,佔用記憶體從80M降到2M.(TaskManager觀察的結果)按 照知秋一葉的說法,這樣調整WorkingSet,將有可能導致缺頁中斷,嚴重影響效能。 但是從使用的情況來看,沒有發現這樣的現象

 

public Form1()         {             InitializeComponent();                        //每1分鐘 檢查一次            System.Timers.Timer timer = new System.Timers.Timer(60 * 1000);            timer.Elapsed += timer_Elapsed;            timer.Start();         }         private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)        {            //1 比較時間是否有效  HH:mm            DateTime starttime = e.SignalTime;            string time = ConfigurationManager.AppSettings["ClearMemory_PerdayTime"];//"05:00"            string dtNow = starttime.ToString("yyyy-MM-dd HH:mm");            DateTime dayDefine = DateTime.Parse(starttime.ToString("yyyy-MM-dd") + " " + time);            if (dayDefine.ToString("yyyy-MM-dd HH:mm") == dtNow)            {                //2 啟動垃圾收集器                ClearMemory();                LogWarning(DateTime.Now.ToLongTimeString() + " :釋放記憶體!");            }        }

注意,引用命名空間:using System.Runtime.InteropServices;

.net中清理記憶體,清理佔用記憶體方式方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.