Ale*_*kov 10 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
}
Run Code Online (Sandbox Code Playgroud)
...我得到一个异常实例"实例的名称"在指定的类别中不存在,并且不理解原因.
PS代码
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<settings>
<performanceCounters enabled="true"/>
</settings>
</system.net>
</configuration>
Run Code Online (Sandbox Code Playgroud)
...包含在App.config中.
小智 0
添加到以前的帖子中,我看到进程的格式类似于 <ProcessName>_<ProcessId> - 取决于您运行应用程序的操作系统(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;
}
Run Code Online (Sandbox Code Playgroud)