用于获取WMI信息的尖锐代码

时间:2012-03-28 09:07:58

标签: c#

如何使用“性能计数器”在c sharp中编码以获取总内存,CPU使用率等WMI信息。

1 个答案:

答案 0 :(得分:1)

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());
                }
            }
        }

要获得虚拟内存,您必须自己做一些研究。