用于获取WMI信息的C sharp代码

本文关键字:sharp 代码 信息 获取 WMI 用于 | 更新日期: 2023-09-27 18:29:18

如何在c sharp中使用"性能计数器"来获取WMI信息,如总内存、cpu使用情况。

用于获取WMI信息的C sharp代码

private static PerformanceCounter cpuCounter;
private static PerformanceCounter memoryCounter;
[...]
cpuCounter = new PerformanceCounter
{
   CategoryName = "Processor",
   CounterName = "% Processor Time",
   InstanceName = "_Total"
};

memoryCounter = new PerformanceCounter
{
    CategoryName = "Memory",
    CounterName = "Available Bytes"
};
[...]
public double CpuUsage
{
   get
   {
      lock (lockToken)
      {
          return Math.Round(cpuCounter.NextValue(), 2);
      }
   }
 }
 public double MemoryUsage
 {
    get
    {
       lock (lockToken)
       {
          return Math.Round(memoryCounter.NextValue() / totalMemory * 100, 2);
       }
    }
  }

总内存:

 using (var searcher = new ManagementObjectSearcher("SELECT totalphysicalmemory FROM Win32_ComputerSystem"))
        {
            using (var wmiData = searcher.Get())
            {
                foreach (var mo in wmiData)
                {
                    totalMemory = long.Parse(mo["totalphysicalmemory"].ToString());
                }
            }
        }

为了获得虚拟内存,你必须自己做一些研究。