基於.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兆之間了.
不信你可以試一試.