c# - 异常:指定类别中不存在实例 'Name of instance'

标签 c# exception performancecounter

当我像这样创建和使用性能计数器时:

private readonly PerformanceCounter _cpuPerformanceCounter;
public ProcessViewModel(Process process)
        {

             _cpuPerformanceCounter = new PerformanceCounter("Process", "% Processor Time", process.ProcessName, true);
        }

public void Update()
        {
            CPU = (int)_cpuPerformanceCounter.NextValue() / Environment.ProcessorCount; // Exception
        }

...我得到一个异常实例“实例名称”在指定的类别中不存在并且不明白为什么。

附言代码

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.net>
    <settings>
      <performanceCounters enabled="true"/>
    </settings>
  </system.net>
</configuration>

...包含在 App.config 中。

最佳答案

除了之前的帖子,我还看到进程的格式类似于 _ - 取决于您运行应用程序的操作系统(Win XP、Win Vista、Win 7、Win 2003 或 2008 Server) .为了有一种可靠的方法来识别您的进程名称以获取其他性能计数器,函数可能如下所示:

    private string ObtainProcessName()
    {
        string baseProcessName;
        string processName = null;
        int processId;
        bool notFound = true;
        int processOptionsChecked = 0;
        int maxNrOfParallelProcesses = 3 + 1;

        try
        {
            baseProcessName = Process.GetCurrentProcess().ProcessName;
        }
        catch (Exception exception)
        {
            return null;
        }

        try
        {
            processId = Process.GetCurrentProcess().Id;
        }
        catch (Exception exception)
        {
            return null;
        }

        while (notFound)
        {
            processName = baseProcessName;
            if (processOptionsChecked > maxNrOfParallelProcesses)
            {
                break;
            }

            if (1 == processOptionsChecked)
            {
                processName = string.Format("{0}_{1}", baseProcessName, processId);
            }
            else if (processOptionsChecked > 1)
            {
                processName = string.Format("{0}#{1}", baseProcessName, processOptionsChecked - 1);
            }

            try
            {
                PerformanceCounter counter = new PerformanceCounter("Process", "ID Process", processName);
                if (processId == (int)counter.NextValue())
                {
                    notFound = !true;
                }
            }
            catch (Exception)
            {
            }
            processOptionsChecked++;
        }
        return processName;
    }

关于c# - 异常:指定类别中不存在实例 'Name of instance',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5832709/

相关文章:

c# - 违反主键约束,无法插入重复键 - 在新的空表中

c# - 从没有按钮的代码更新 WinForm 标签值

c# - 将没有 LinqExpression 的自定义助手转换为使用 LinqExpression 的自定义助手

java - 如何在批处理中获取包含异常的精确sql查询

c# - 获取 Mono 中的处理器时间百分比

c# - 如何处理ServiceStack中的多个服务?

JAVA - 不可写 channel 异常

c++ - 无法在另一个类中实例化模板化类

Angular 性能跟踪

c# - 检索计算机上的 RAM 总量