C#内存占用释放

序言

系统启动起来以后,内存占用越来越大,使用析构函数、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
复制代码

Winform如何降低系统内存

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

资料

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

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

NET资源泄露与处理方案

posted @   ~沐风  阅读(2704)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2016-11-17 Mongodb Gridfs

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示