避免使用PerformanceCounter.NextValue的InvalidOperationException异常

时间:2014-12-20 09:09:12

标签: c# .net exception performancecounter

var counter = new PerformanceCounter{};
counter.CategoryName = "Process";
counter.CounterName = "% Processor Time";
counter.InstanceName = someProcessName;

if ( PerformanceCounterCategory.InstanceExists( someProcessName, "Process" ) )
{
    // For any reason the process terminates EXACTLY at this point
    counter.NextValue();
    // we'll get a InvalidOperationException exception here
}

是否有可能以安全的方式使用PerformanceCounter.NextValue方法。仅仅为了记录,我知道它不太可能有这种情况。

2 个答案:

答案 0 :(得分:0)

查看MSDN - The instance is not correctly associated with a performance counter时抛出InvalidOperationException。

PerformanceCounter.NextValue Method

尝试使用RawValue属性初始化您的计数器:

// Initialize the counter.
counter.RawValue = Stopwatch.GetTimestamp();

如果这不会有帮助 - 检查类别和计数器名称是否有效

答案 1 :(得分:0)

像这样使用try-catch:

var counter = new PerformanceCounter{};
counter.CategoryName = "Process";
counter.CounterName = "% Processor Time";
counter.InstanceName = someProcessName;
try
{
   if ( PerformanceCounterCategory.InstanceExists( someProcessName, "Process" ) )
   {
       // For any reason the process terminates EXACTLY at this point
       counter.NextValue();
   }
}
catch(InvalidOperationException error)
{
   //deal with exception
}