Skip to content

根据进程 ID 获取进程 CPU 占用和内存占用等信息(C#)

Published: at 14:27

根据进程 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


原文链接: https://blog.jgrass.cc/posts/csharp-cpu-memory-info/

本作品采用 「署名 4.0 国际」 许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。