C# 内存回收

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

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

 

        #region 内存回收
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        /// 
        /// 释放内存
        /// 
        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

 

你可能感兴趣的:(C# 内存回收)