1. 程式人生 > >C#釋放記憶體的方法

C#釋放記憶體的方法

原文:https://blog.csdn.net/zsy619/article/details/79181719

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

如何釋放記憶體:

[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(Process.GetCurrentProcess().Handle,
-1, -1);      } }

如何獲取當前應用佔用的記憶體大小:

/// <summary>
/// 釋放記憶體
/// </summary>
public static void ClearMemory()
{
     //獲得當前工作程序
     Process proc = Process.GetCurrentProcess();
     long usedMemory = proc.PrivateMemorySize64;
     
if (usedMemory > 1024 * 1024 * 20)      {          GC.Collect();          GC.WaitForPendingFinalizers();          if (Environment.OSVersion.Platform == PlatformID.Win32NT)          {              SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);          }      } }