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

我正在跟踪同一应用程序的多个实例,并需要获取这两个进程的内存和cpu使用。但是,我似乎无法找出使用性能计数器的方法,并知道哪个结果是针对哪个进程。我已经看到我可以追加#1等等到结尾的名字来获得每个结果,但这并不告诉我哪一个是哪个进程。

如何确定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;
This answer相关问题可能会起作用:

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 ...");
}
翻译自:https://stackoverflow.com/questions/9115436/performance-counter-by-process-id-instead-of-name

转载注明原文:c# – 按进程ID而不是名称的性能计数器?