Lou*_*hys 50

对于每个流程数据:

Process p = /*get the desired process here*/;
PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName);
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
while (true)
{
    Thread.Sleep(500);
    double ram = ramCounter.NextValue();
    double cpu = cpuCounter.NextValue();
    Console.WriteLine("RAM: "+(ram/1024/1024)+" MB; CPU: "+(cpu)+" %");
}
Run Code Online (Sandbox Code Playgroud)

性能计数器还有其他计数器,而不是工作集和处理器时间.

  • 需要注意的是Sleep是必需的,调用NextValue,然后Sleep为500-100,然后调用NextValue来获取实际值,如果先调用NextValue然后使用该值并继续下一个进程,它将始终为0处理器%的值,RAM值无论如何都有效. (6认同)
  • 传递给PerformanceCounter构造函数的可能值列表在哪里?我找不到任何地方. (2认同)

tgo*_*sch 5

如果您使用的是 .NET Core,则这System.Diagnostics.PerformanceCounter不是一个选项。试试这个:

System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
long ram = p.WorkingSet64;
Console.WriteLine($"RAM: {ram/1024/1024} MB");
Run Code Online (Sandbox Code Playgroud)