zoukankan      html  css  js  c++  java
  • 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资源泄露与处理方案

  • 相关阅读:
    python 字符串常用操作
    markdown 基础语法
    网络安全入门的16个基本问题
    Linux中20个crontab例子
    使用python爬取一个网页里表格的内容
    浅谈python的深浅拷贝
    Linux中设置普通用户可以su和sudo
    iptables四表五链
    CentOS7编译安装NFS
    源码安装csvn
  • 原文地址:https://www.cnblogs.com/cnki/p/11876909.html
Copyright © 2011-2022 走看看