在C# winform应用程序中,用以下代码可以进行一些内存使用的优化
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
/// <summary>
/// 包含各种内存管理、优化的方法
/// </summary>
public class Memory
{
private static readonly Version myVersion = new Version(1, 0);
/// <summary>
/// 将当前进程的内存占用尺寸设置到最小
/// </summary>
/// <returns>0为成功,-1为失败</returns>
public static int SetProcessMemoryToMin()
{
return SetProcessMemoryToMin(Process.GetCurrentProcess().Handle);
}
/// <summary>
/// 将内存占用尺寸设置到最小
/// </summary>
/// <param name="SetProcess">需要设置内存使用范围的程序进程句柄,一般为当前进程, 如:System.Diagnostics.Process.GetCurrentProcess().Handle</param>
/// <returns>0为成功,-1为失败</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);
}