C# 按进程 ID 而不是名称的性能计数器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9115436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:02:55  来源:igfitidea点击:

Performance Counter by Process ID instead of name?

c#performancecounter

提问by JeremyK

I am tracking multiple instances of the same application and need to get the memory and cpu use of both processes. However, I cant seem to figure out a way to use the performance counter and know which result is for which process. I have seen that I can append #1 and such to the end of the name to get results for each, but that doesn't tell me which one is for which process.

我正在跟踪同一应用程序的多个实例,需要获取两个进程的内存和 CPU 使用情况。但是,我似乎无法找到一种使用性能计数器并知道哪个结果适用于哪个进程的方法。我已经看到我可以将 #1 等附加到名称的末尾以获得每个的结果,但这并没有告诉我哪个用于哪个进程。

How can I determine the ProcessId or pass the process ID to the counter to get the result per each process with same name?

如何确定 ProcessId 或将进程 ID 传递给计数器以获取每个具有相同名称的进程的结果?

PerformanceCounterCPU.CategoryName = "Process";
PerformanceCounterCPU.CounterName = "% Processor Time";
PerformanceCounterCPU.InstanceName = proc.ProcessHandle.ProcessName;

PerformanceCounterMemory.CategoryName = "Process";
PerformanceCounterMemory.CounterName = "Working Set - Private";
PerformanceCounterMemory.InstanceName = proc.ProcessHandle.ProcessName;

采纳答案by M.Babcock

This answerto a related question might work:

这个相关问题的答案可能有效:

private static string GetProcessInstanceName(int pid)
{
  PerformanceCounterCategory cat = new PerformanceCounterCategory("Process");

  string[] instances = cat.GetInstanceNames();
  foreach (string instance in instances)
  {

     using (PerformanceCounter cnt = new PerformanceCounter("Process",  
          "ID Process", instance, true))
     {
        int val = (int) cnt.RawValue;
        if (val == pid)
        {
           return instance;
        }
     }
  }
  throw new Exception("Could not find performance counter " + 
      "instance name for current process. This is truly strange ...");
}

回答by Seb Wills

If you don't mind a machine-wide registry change, you can configure Windows to use the form ProcessName_ProcessID for Perf Counter instance names, rather than appending #1, #2, etc:

如果您不介意机器范围的注册表更改,您可以将 Windows 配置为对 Perf Counter instance names 使用 ProcessName_ProcessID 形式,而不是附加 #1、#2 等:

Create DWORD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance\ProcessNameFormatand set its value to 2.

创建 DWORDHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance\ProcessNameFormat并将其值设置为 2。

If you do stick with the #1, #2 etc form, beware that the instance name for a given process can change during the process' lifetime!

如果您坚持使用 #1、#2 等形式,请注意给定流程的实例名称可能会在流程的生命周期内更改