本人開發的winform程序,用到了線程池,用到了多線程循環讀取數據更新,用到了第三方控件,程序啓動時內存佔用已經在>30M這個水平了,並且發現只要多線程啓動,就會內存不斷地增加,雖然使用了GC.Collect()但不管是連續使用1次還是兩次並不能實際解決問題,只不過是使得每次增加的變動減少到4k左右而已。於是經過各種蒐羅發現瞭如下方法進行內存回收,經過使用,效果非常好,目前基本穩定在3.3M左右,這樣就算增加了,但是定期回收了,又變回這個低水平了。
從>30M到>3M這個差異還是很大的,特此記錄下來經驗,供有需要的人蔘考:
using System.Runtime.InteropServices; //可以用DllImport了
#region 內存回收
[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
/// <summary>
/// 釋放內存
/// </summary>
public static void ClearMemory()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}
#endregion
在你認爲合適的地方調用ClearMemory()即可。