c#的winform程序主动触发垃圾回收释放内存

参考:https://bbs.csdn.net/topics/300138657

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

c#的winform程序代码上的写法没有使用stream后不关闭的情况,但运行时间长了,会存在内存明显飙高,使用定时器定时调用以下方法,通知系统进行垃圾回收,并把不频繁使用的代码从物理内存放到磁盘虚拟内存中

 

/// 
        /// 刷新内存
        /// 
        public static void FlushMemory()
        {
            GarbageCollect();

            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
            }
        }

        /// 
        /// 主动通知系统进行垃圾回收
        /// 
        public static void GarbageCollect()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

        /// 
        /// 把不频繁执行或者已经很久没有执行的代码,没有必要留在物理内存中,只会造成浪费;放在虚拟内存中,等执行这部分代码的时候,再调出来
        /// 
        /// 
        /// 
        /// 
        /// 
        [DllImport("kernel32.dll")]
        public static extern bool SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);

 

 

 

 

你可能感兴趣的:(c#)