c# - Exception: Instance 'Name of instance' does not exist in the specified Category -


when create , use performance counters this:

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         } 

... exception instance 'name of instance' not exist in specified category , don't understand why.

p.s. code

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

... included in app.config.

adding on previous posts, have seen processes being formatted <processname>_<processid> - depending on os running app on (win xp, win vista, win 7, win 2003 or 2008 server). in order have reliable way identify process name obtaining other performance counters down road, function this:

    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;     } 

Comments