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方法。仅仅为了记录,我知道它不太可能有这种情况。
答案 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
}