.NET Framework回收內存操作細節披露
.NET Framework中實際上有很多應用技巧需要我們在具體操作中去慢慢發現,從而掌握這些提高開發效率的應用技巧。基于.NET Framework 的Windows應用程序,你會發現你對程序的操作越多,占用的內存會不斷向上飆升,即使你結束了長時間運行的操作.這種情況對于一個非常小的應用都是這樣.#t#
這種情況一般并不是.Net 內存泄露,而是因為.Net沒有即時回收你分配的內存。下面是從一個朋友那兒搞到的一段代碼,它能夠幫助你即時實現.NET Framework回收內存的操作.
- public class RevokeMemory
- {
- public static void ReduceMemoryFootPrint()
- {
- int currentMinWorkingSetValue = 0;
- int currentMaxWorkingSetValue = 0;
- Process currentProcess = Process.
GetCurrentProcess(); - try
- {
- if(GetProcessWorkingSetSize(current
Process.Handle, out currentMinWorking
SetValue, out currentMaxWorkingSetValue)) - {
- currentProcess.MinWorkingSet = (IntPtr)
currentMinWorkingSetValue; - }
- }
- catch(Exception err)
- {
- string additionalInfo = "MinWorkingSet
value is set to: " + currentMinWorking
SetValue.ToString(); - additionalInfo += " Process In Error:
" + currentProcess.ProcessName; - //Log error message
- }
- }
- [DllImport("kernel32.dll")]
- public static extern bool GetProcess
WorkingSetSize( IntPtr proc, out int
min, out int max ); - [DllImport("kernel32.dll")]
- public static extern bool SetProcess
WorkingSetSize( IntPtr proc, int min, int max ); - }
.NET Framework回收內存調用的時機:
1. 主界面上做一個計時器,每間隔一定的時間進行調用,但鄙人認為這種效果并不好。在你進行長時間運行的操作之前。需要禁止它。
2.每完成一個大的操作或者比較消耗內存的操作之后,調用。
本人做了一個.NET Framework回收內存的測試,以前幾時兆的內存飆升,現在總的消耗的內存都在幾兆到30兆之間了.