如何使用“性能计数器”在c sharp中编码以获取总内存,CPU使用率等WMI信息。
答案 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());
}
}
}
要获得虚拟内存,您必须自己做一些研究。