How to get free(available) physical memory/获取可用的内存

时间:2021-03-15 16:56:12

 How to get free physical memory/获取可用的内存

 

在.Net中可以通过如下几种方式获取可用内存:

  1. 性能计数器(PerformanceCounter)
  2. 设备信息(Devices.ComputerInfo)
  3. Windows管理(WMI)

当然也可引用windows的dll,调用winAPI来获取.相对而言,下面三种比较方便.

 

Code:  

namespace ConsoleApplication3

{

using System;

using System.Diagnostics;

using Microsoft.VisualBasic.Devices;

using System.Management;

public class Program

 

{

static void Main(string[] args)

{

long freeMemory = GetAvailableMemoryInByteByPerformanceCounter();

Console.WriteLine(freeMemory.ToString());

freeMemory = GetAvailablePhysicalMemoryInByteByDevices();

Console.WriteLine(freeMemory.ToString());

freeMemory = GetAvailablePhysicalMemoryInByteByWMI();

Console.WriteLine(freeMemory.ToString());

Console.Read();

}

private static long GetAvailableMemoryInByteByPerformanceCounter()

{

//Available Bytes, Available KBytes, Available MBytes

 

long freeMemory = 0;

using (PerformanceCounter pc = new PerformanceCounter("Memory", "Available Bytes"))

{

freeMemory = Convert.ToInt64(pc.NextValue());

}

return freeMemory;

}

public static long GetAvailablePhysicalMemoryInByteByDevices()

{

ComputerInfo computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();

return (long)computerInfo.AvailablePhysicalMemory;

}

public static long GetAvailablePhysicalMemoryInByteByWMI()

{

long freeMemory = 0;

string query = "SELECT * FROM Win32_OperatingSystem";

using (ManagementObjectSearcher sucher = new ManagementObjectSearcher(query))

{

using (ManagementObjectCollection oReturnCollection = sucher.Get())

{

foreach (ManagementObject m in oReturnCollection)

{

freeMemory = Convert.ToInt64(m["FreePhysicalMemory"].ToString());

}

}

}

return freeMemory << 10;

}

}

}

 

Result:

1007013888
1006624768
1005694976