C# 内存回收

开发完成之后发现自己写的程序内存占用太高,找到如下解决方案

使用了一个timer每2s调用一次ClearMemory()

        #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);
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            ClearMemory();
        }

        #endregion
原文地址:https://www.cnblogs.com/huanjun/p/10832099.html