zoukankan      html  css  js  c++  java
  • 基于.NET Framework 的Windows应用程序如何回收内存

            基于.NET Framework 的Windows应用程序,你会发现你对程序的操作越多,
    占用的内存会
    不断向上飙升,即使你结束了长时间运行的操作.这种情况对于一个非常小的应用都是这样.
    这种情况一般并不是.Net 内存泄露,而是因为.Net没有即时回收你分配的内存。下面是从一个朋友那儿搞到的一段代码,
    它能够帮助你即时回收内存.

    public class RevokeMemory
        {
            
    public static void ReduceMemoryFootPrint()
            {
                
    int currentMinWorkingSetValue = 0;
                
    int currentMaxWorkingSetValue = 0;
                Process currentProcess 
    = Process.GetCurrentProcess();

                
    try
                {
                    
    if(GetProcessWorkingSetSize(currentProcess.Handle, out currentMinWorkingSetValue, out currentMaxWorkingSetValue))
                    {
                        currentProcess.MinWorkingSet 
    = (IntPtr)currentMinWorkingSetValue;
                    }
                }
                
    catch(Exception err)
                {
                    
    string additionalInfo = "MinWorkingSet value is set to: " + currentMinWorkingSetValue.ToString();
                    additionalInfo 
    += " Process In Error: " + currentProcess.ProcessName;
                    
    //Log error message
                }
            }

            [DllImport(
    "kernel32.dll")]
            
    public static extern bool GetProcessWorkingSetSize( IntPtr proc, out int min, out int max );

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

        }

    调用的时机:
    1. 主界面上做一个计时器,每间隔一定的时间进行调用,但鄙人认为这种效果并不好。在你进行长时间运行的操作之前。需要禁止它。
    2.每完成一个大的操作或者比较消耗内存的操作之后,调用。
    本人做了一个测试,以前几时兆的内存飙升,现在总的消耗的内存都在几兆到30兆之间了.
    不信你可以试一试.

  • 相关阅读:
    hdu1686 最大匹配次数 KMP
    洛谷 P5057 [CQOI2006]简单题(树状数组)
    洛谷 P5020 货币系统
    洛谷 P5019 铺设道路(差分)
    洛谷 P1119 灾后重建(Floyd)
    洛谷 P1082 同余方程(同余&&exgcd)
    洛谷 P2384 最短路
    洛谷 P3371 【模板】单源最短路径(弱化版) && dijkstra模板
    洛谷 P1387 最大正方形
    洛谷 P2866 [USACO06NOV]糟糕的一天Bad Hair Day
  • 原文地址:https://www.cnblogs.com/SharkXu/p/RevokeMemory.html
Copyright © 2011-2022 走看看