远程性能计数器System.InvalidOperationException

时间:2014-12-17 15:05:53

标签: c# .net performancecounter system.diagnostics

我有2段代码偶尔抛出错误。如果我在server.FullyQualifiedDomainName中定义的服务器上本地运行应用程序,我从未得到任何错误。如果我远程运行应用程序并通过网络读取计数器,我将得到下面定义的错误。错误不会一直发生。我通过网络读取性能计数器的地方有点不稳定......无论如何要获得更可靠的响应?

读取类别的代码:

var windowsCounterCategory = new PerformanceCounterCategory(counterCategory, server.FullyQualifiedDomainName); 
var serviceGuidsStr = windowsCounterCategory.GetInstanceNames();

错误:

System.InvalidOperationException: Could not Read Category Index: 8324.
   at System.Diagnostics.CategorySample..ctor(Byte[] data, CategoryEntry entry, PerformanceCounterLib library)
   at System.Diagnostics.PerformanceCounterLib.GetCategorySample(String category)
   at System.Diagnostics.PerformanceCounterLib.GetCategorySample(String machine, String category)
   at System.Diagnostics.PerformanceCounterCategory.GetCounterInstances(String categoryName, String machineName)
   at System.Diagnostics.PerformanceCounterCategory.GetInstanceNames()

读取计数器值的代码:

   using (var perfomanceCounter = new PerformanceCounter(categoryName, counterName, instanceId, Service.Server.FullyQualifiedDomainName))
   {
      var counterValue = perfomanceCounter.RawValue;
      log.Trace("Read counter value " + counterValue.ToString());
      return counterValue;
   }

错误:

System.InvalidOperationException: Could not Read Category Index: 8324.
   at System.Diagnostics.CategorySample..ctor(Byte[] data, CategoryEntry entry, PerformanceCounterLib library)
   at System.Diagnostics.PerformanceCounterLib.GetCategorySample(String category)
   at System.Diagnostics.PerformanceCounterLib.GetCategorySample(String machine, String category)
   at System.Diagnostics.PerformanceCounter.NextSample()
   at System.Diagnostics.PerformanceCounter.get_RawValue()

1 个答案:

答案 0 :(得分:0)

通过网络阅读性能计数器似乎并不是非常可靠。我决定使用Microsoft Transient Fault Handling库(v 6.0,在nuget上搜索topaz)并实施重试策略。通常一次重试就足以得到一个有效的答案(没有例外),有时可能需要两次重试。

我实施了一种瞬态故障检测策略,用于检查特定网络相关错误(System.InvalidOperationException: Could not Read Category Index: 8324.

public class PerformanceCounterStrategy : ITransientErrorDetectionStrategy
{
  public bool IsTransient(Exception ex)
  {
    return ex.GetType() == typeof (InvalidOperationException);
  }
}

以下是我实施的重试策略:

var retryStrategy = new Incremental(3, 2, 2);
var retryPolicy = new RetryPolicy<PerformanceCounterTransientStrategy>(retryStrategy);

retryPolicy.ExecuteAction(() =>
  {
    var windowsCounterCategory = new PerformanceCounterCategory(counterCategory, server.FQDN);
    var guidsStr = windowsCounterCategory.GetInstanceNames();

  });