Memory recovery code for C

  • 2020-12-05 17:20:28
  • OfStack

The example in this article describes the memory recovery method of C#. Share to everybody for everybody reference. Specific implementation methods are as follows:

The following example code is to call the underlying win32 operation to achieve memory recovery.

[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
/// <summary>
/// Free memory
/// </summary>
public static void ClearMemory()
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
    if (Environment.OSVersion.Platform == PlatformID.Win32NT)
    {
 SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
    }
}

Hopefully this article has helped you with your C# programming.


Related articles: