首页 > Windows开发 > 详细

C#内存占用释放

时间:2019-11-17 17:11:36      阅读:132      评论:0      收藏:0      [点我收藏+]

序言

系统启动起来以后,内存占用越来越大,使用析构函数、GC.Collect什么的也不见效果,后来查了好久,找到了个办法,就是使用 SetProcessWorkingSetSize函数。这个函数是Windows API 函数。下面是使用的方法:

技术分享图片
[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet =
System.Runtime.InteropServices.CharSet.Ansi, SetLastError = true)]
private static extern int SetProcessWorkingSetSize(IntPtr process, int minimumWorkingSetSize, int maximumWorkingSetSize);

public void Dispose()
{
    GC.Collect();
    GC.SuppressFinalize(this);

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

C# 出来的Winform程序内存占用默认比较大,这个方法可以极大优化程序内存占用。 其实吧,百度了下,这个函数是将程序的物理内存尽可能转换为虚拟内存,大大增加硬盘读写,是不好的。

技术分享图片
 #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);  
             }  
         }  
 #endregion 
View Code

资料

https://blog.csdn.net/bdstjk/article/details/8482711

C#内存占用释放

原文:https://www.cnblogs.com/cnki/p/11876909.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!