根据进程 ID 获取进程 CPU 占用和内存占用等信息(C#)
代码参考
PerformanceCounter? cpuCounter = null;
PerformanceCounter? ramCounter = null;
PerformanceCounter? ramCounter2 = null;
// PerformanceCounter? ramCounter3 = null;
var performanceCounterCategory = new PerformanceCounterCategory("Process");
var instanceNames = performanceCounterCategory.GetInstanceNames();
foreach (var instanceName in instanceNames)
{
try
{
var counter = new PerformanceCounter("Process", "ID Process", instanceName, true);
if (counter.RawValue == Pid)
{
cpuCounter = new PerformanceCounter("Process", "% Processor Time", instanceName);
ramCounter = new PerformanceCounter("Process", "Working Set", instanceName);
ramCounter2 = new PerformanceCounter("Process", "Private Bytes", instanceName);
// ramCounter3 = new PerformanceCounter(".NET CLR Memory", "# Gen 2 Collections", instanceName);
break;
}
}
catch (Exception e)
{
continue;
}
}
if (cpuCounter == null || ramCounter == null || ramCounter2 == null)
{
return null;
}
var cpu = cpuCounter.NextValue();
var ram = ramCounter.NextValue() / (1024.0 * 1024);
var ram2 = ramCounter2.NextValue() / (1024.0 * 1024);
// var ram3 = ramCounter3.NextValue() / (1024.0 * 1024);
参考资料
c# - Performance Counter by Process ID instead of name? - Stack Overflow
.net - Get CPU Usage for Process by Process ID - Stack Overflow