当我像这样创建和使用性能计数器时:
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 中。
最佳答案
除了之前的帖子,我还看到进程的格式类似于
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/