C# Winform应用程序内存回收

关于C#Winform应用程序如何降低系统内存空间占用

1、使用性能测试工具dotTrace 3.0,它能够计算出你程序中那些代码占用内存较多

2、强制垃圾回收
3、多dispose,close

4、用timer,每几秒钟调用:SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);

5、发布的时候选择Release

6、注意代码编写时少产生垃圾,比如String + String就会产生大量的垃圾,可以用StringBuffer.Append

7、this.Dispose();    this.Dispose(True);   this.Close();    GC.Collect(); 
8、注意变量的作用域,具体说某个变量如果只是临时使用就不要定义成成员变量。GC是根据关系网去回收资源的。

9、检测是否存在内存泄漏的情况

定期清理执行垃圾回收代码:
在程序中用一个计时器,每隔几秒钟调用一次该函数,打开任务管理器,你会有惊奇的发现,相当于定时进行内存回收

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

        public void FlushMemory() {
            GC.Collect() ;
            GC.WaitForPendingFinalizers() ;
            if(Environment.OSVersion.Platform == PlatformID.Win32NT) {
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1) ;
            }
        }
   }
原文地址:https://www.cnblogs.com/lanshy/p/3061911.html