.NET Framework回收内存操作细节披露

来源:互联网 发布:部落冲突法术工厂数据 编辑:程序博客网 时间:2024/04/29 00:25

.NET Framework中实际上有很多应用技巧需要我们在具体操作中去慢慢发现,从而掌握这些提高开发效率的应用技巧。基于.NET Framework 的Windows应用程序,你会发现你对程序的操作越多,占用的内存会不断向上飙升,即使你结束了长时间运行的操作.这种情况对于一个非常小的应用都是这样.

这种情况一般并不是.Net 内存泄露,而是因为.Net没有即时回收你分配的内存。下面是从一个朋友那儿搞到的一段代码,它能够帮助你即时实现.NET Framework回收内存的操作.

  1. public class RevokeMemory  
  2. {  
  3. public static void ReduceMemoryFootPrint()  
  4. {  
  5. int currentMinWorkingSetValue = 0;  
  6. int currentMaxWorkingSetValue = 0;  
  7. Process currentProcess = Process.
    GetCurrentProcess();  
  8. try  
  9. {  
  10. if(GetProcessWorkingSetSize(current
    Process.Handle, out currentMinWorking
    SetValue, out currentMaxWorkingSetValue))  
  11. {  
  12. currentProcess.MinWorkingSet = (IntPtr)
    currentMinWorkingSetValue;  
  13. }  
  14. }  
  15. catch(Exception err)  
  16. {  
  17. string additionalInfo = "MinWorkingSet
     value is set to: "
     + currentMinWorking
    SetValue.ToString();  
  18. additionalInfo += " Process In Error: 
    " + currentProcess.ProcessName;  
  19. //Log error message  
  20. }  
  21. }  
  22. [DllImport("kernel32.dll")]  
  23. public static extern bool GetProcess
    WorkingSetSize( IntPtr proc, out int 
    min, out int max );  
  24. [DllImport("kernel32.dll")]  
  25. public static extern bool SetProcess
    WorkingSetSize( IntPtr proc, int min, int max );  

.NET Framework回收内存调用的时机:

1. 主界面上做一个计时器,每间隔一定的时间进行调用,但鄙人认为这种效果并不好。在你进行长时间运行的操作之前。需要禁止它。

2.每完成一个大的操作或者比较消耗内存的操作之后,调用。

本人做了一个.NET Framework回收内存的测试,以前几时兆的内存飙升,现在总的消耗的内存都在几兆到30兆之间了.

原创粉丝点击