内存优化软件使用的是一种手段

继续上一篇的解释:

--------------------------------

一个空白WinForm在任务管理器中都占用几十兆内存,的确有点可怕!通常有3种方法:                 

1. 不要管他。 

CLR & GC 会自动管理内存占用,根据当前环境参数自动调整,这样会得到一个最佳化的运行效率。

2. 设置托管程序进程允许的最大工作集大小。

 

1   Process.GetCurrentProcess().MaxWorkingSet  =  (IntPtr)( 1024   *   1024   *   5 );

3. 使用SetProcessWorkingSetSize,将部分物理内存占用转移到虚拟内存。

 

1   [DllImport( " kernel32.dll " )]
2   public   static   extern   bool  SetProcessWorkingSetSize(IntPtr proc,  int  min,  int  max );
3       
4   private   void  button1_Click( object  sender, System.EventArgs e)
5   {
6     SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle,  - 1 - 1 );
7   }

注意第2,3种方法在某种程度上都会影响程序的性能。设置一个合理的工作集大小,或者在程序启动后,空闲时(Application.Idle)使用SetProcessWorkingSetSize,还是可以的,毕竟减少内存占用对于系统运行也有一定的益处。

 

使用事例:

 

 1  private   void  timer1_Tick( object  sender, System.EventArgs e)
 2  {
 3     //  使用定时器将当前物理内存占用(MB)添加到列表框中。
 4     string  s  =   string .Format( " {0} " , Process.GetCurrentProcess().WorkingSet  /   1024   /   1024 );
 5     this .listBox1.Items.Insert( 0 , s);
 6  }
 7  
 8  [DllImport( " kernel32.dll " )]
 9  public   static   extern   bool  SetProcessWorkingSetSize(IntPtr proc,  int  min,  int  max );
10      
11  private   void  button1_Click( object  sender, System.EventArgs e)
12  {
13     //  减少内存占用
14    SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle,  - 1 - 1 );
15  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值