TotalPhysicalMemory来自VisualBasic.设备与WMI Win32_PhysicalMemory

本文关键字:WMI Win32 PhysicalMemory 来自 VisualBasic TotalPhysicalMemory | 更新日期: 2023-09-27 18:07:07

所以我的应用程序需要知道可用的总内存。至少有4种不同的方式存在,就我而言:

  • 查询Windows管理工具(WMI)
  • 从Microsoft.VisualBasic.Devices.ComputerInfo.TotalPhysicalMemory获取
  • 查询WinAPI
  • 使用P-Invoke

我喜欢前两个,但是它们在我的机器上给出的结果略有不同(每个2GB的2个棒,Windows 8.1 64位)。

我用来从VisualBasic dll中获取它的代码:

class Program
{
    private static readonly Lazy<ComputerInfo> ComputerInfo = new Lazy<ComputerInfo>();
    public static ulong TotalRam => ComputerInfo.Value.TotalPhysicalMemory;
    static void Main(string[] args)
    {
        Console.WriteLine("Total RAM from ComputerInfo: {0} bytes", TotalRam);
        // Result: Total RAM from ComputerInfo: 4292902912 bytes
    }
}

我用来从Windows Management获取它的代码:

class Program
{
    public static IEnumerable<object> GetResults(string win32ClassName, string property)
    {
        return (from x in new ManagementObjectSearcher("SELECT * FROM " + win32ClassName).Get().OfType<ManagementObject>()
                select x.GetPropertyValue(property));
    }
    public static ulong? TotalInstalledBytes
    {
        get
        {
            var values = GetResults("Win32_PhysicalMemory", "Capacity");
            ulong? sum = null;
            foreach (var item in values)
            {
                var casted = item as ulong?;
                if (casted.HasValue)
                {
                    if (sum == null) sum = 0;
                    sum += casted.Value;
                }
            }
            return sum;
        }
    }
    static void Main(string[] args)
    {
        Console.WriteLine("Total RAM from WMI: {0} bytes", TotalInstalledBytes);
        // Result: Total RAM from WMI: 4294967296 bytes
    }
}

差异略小于2 MB, 2064384字节或2016 kB准确。我的问题是:为什么会这样?

我的猜测是:

  • VisualBasic ComputerInfo返回从操作系统看到的内存透视图,而WMI使用制造商'硬编码'值
  • VisualBasic ComputerInfo返回实际存在的内存看来,市售的记忆棒很少有这种功能确切的字节数),而WMI使用制造商的"硬编码"值

感谢您的回复

TotalPhysicalMemory来自VisualBasic.设备与WMI Win32_PhysicalMemory

这可能与您的情况有关:

TotalPhysicalMemory

物理内存的总大小。请注意,在某些情况下,此属性可能不会返回物理内存的准确值。例如,如果BIOS正在使用某些物理内存,则不准确。要获得准确的值,请使用Win32_PhysicalMemory中的Capacity属性。