When you list the instance names in the process performance counter (performancecounter named process), you will find that to distinguish the same process name, the returned process name may be xxx #1, xxx #2 ...... Represents the first XXX process with duplicate names and the second XXX process with duplicate names.
For example, this Code:
VaR Category = new performancecountercategory ("process ");
String [] names = category. getinstancenames ();
Result (on my computer ):
Multiple processes in svchost are identified by # XXX to avoid the same name.
The problem arises, which directly shows that the name is not beautiful, and we do not know which svchost is the specific svchost of the above pile of svchost # XXX, they are numbered by no logic. How does one convert the irregular process name returned by performancecounter to the process object it represents?
The release of the bell is also required by the person who is in the ring ...... The solution depends on the performancecounter of the process type. At this time, relying on another counter: ID process, it can return the PID of a process. In this way, the PID can be queried through these names. With the PID, the process represented by it can be easily found.
For example, this code section (for demonstration only, Please modify it as needed)
// + Using system. Diagnostics
Static void main ()
{
VaR Category = new performancecountercategory ("process ");
String [] names = category. getinstancenames (). Select (name =>
{
VaR counter = new performancecounter ("process", "ID process", name );
VaR id = counter. nextvalue ();
Return string. Format ("PID: {0}-{1}", ID, trimstring (name ));
}). Toarray ();
}
// Try to remove the # character in the process name
Static string trimstring (string name)
{
VaR Pos = Name. indexof ('#');
If (Pos! =-1)
Return name. substring (0, POS );
Return name;
}
Query results of two segments of code:
Download the current version of the program and source code
Download Page
Note: the link is the Microsoft SkyDrive page. When downloading, use a browser to download it directly. Some download tools may not be available for downloading.
Source code environment: Visual C # express 2010