winfrom降低系统内存占用的方法

1、使用性能测试工具dotTrace 3.0,它能够计算出你程序中哪些代码占用内存较多
2、强制垃圾回收 this.Dispose();    this.Dispose(True);   this.Close();    GC.Collect();
3、用timer,每几秒钟调用:SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
4、发布的时候选择Release
5、注意代码编写时少产生垃圾,比如String + String就会产生大量的垃圾,可以用StringBuffer.Append
6、注意变量的作用域,具体说某个变量如果只是临时使用就不要定义成成员变量。GC是根据关系网去回收资源的。
7、检测是否存在内存泄漏的情况。

 

定期清理执行垃圾回收的代码:

用方法:在窗口程序中用一个timer计时器,每隔几秒钟调用一次该释放内存的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)
                {
                    //FrmMian为我窗体的类名
                    FrmMian.SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                }
            }
            #endregion

--以上内容参考转自:https://blog.csdn.net/qq15577969/article/details/89880538

posted @ 2019-07-31 15:12  Morning=Sunshine  阅读(154)  评论(0)    收藏  举报