In depth analysis of C memory management and optimization methods

  • 2020-05-12 03:05:09
  • OfStack

In the C# winform application, some memory usage optimizations can be made with the following code

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
/// <summary>
///  Contains a variety of memory management, optimization methods 
/// </summary>
    public class Memory
    {
        private static readonly Version myVersion = new Version(1, 0);
        /// <summary>
        ///  Sets the current process's memory footprint to a minimum 
        /// </summary>
        /// <returns>0 For success ,-1 For failure </returns>
        public static int SetProcessMemoryToMin()
        {
            return SetProcessMemoryToMin(Process.GetCurrentProcess().Handle);
        }
        /// <summary>
        ///  Set the memory footprint size to minimum 
        /// </summary>
        /// <param name="SetProcess"> You need to set the program process handle for the memory usage range, 1 As the current process,   Such as: System.Diagnostics.Process.GetCurrentProcess().Handle</param>
        /// <returns>0 For success ,-1 For failure </returns>
        public static int SetProcessMemoryToMin(IntPtr SetProcess)
        {
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                return SetProcessWorkingSetSize(SetProcess, -1, -1);
            }
            return -1;
        }
        [DllImport("kernel32.dll")]
        private static extern int SetProcessWorkingSetSize(IntPtr hProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize);
    }


Related articles: