递增自定义性能计数器.net 4.0 Windows 7

本文关键字:Windows net 自定义 性能计数器 | 更新日期: 2023-09-27 17:58:27

我在Windows7上递增自定义性能计数器时遇到了一点问题。创建了Category,创建了Counters,但调用"Increment()"或设置"RawValue"似乎没有效果。例如,Increment()的返回值保持为0L。

以下代码是一个控制台应用程序,需要以管理员身份运行才能创建类别。调试通过演示了上述症状。

非常感谢您的帮助。

class Program
{
    private static string _category = "MyCustomCounters";
    static void Main(string[] args)
    {
        var deleteIfExists = false;
        if (args.Any())
        {
            if (args.Count() > 0)
            {
                _category = args[0];
            }
            if (args.Count() > 1)
            {
                deleteIfExists = args[1].ToUpper() == bool.TrueString.ToUpper();
            }
        }
        CreateCustomCounters(_category, deleteIfExists);
    }
    private static void CreateCustomCounters(string category, bool deleteIfExists)
    {
        if (deleteIfExists && PerformanceCounterCategory.Exists(category))
        {
            PerformanceCounterCategory.Delete(category);
        }
        if (!PerformanceCounterCategory.Exists(category))
        {
            CounterCreationDataCollection counterCollection = new CounterCreationDataCollection();
            // add a counter tracking operations per second
            CounterCreationData opsPerSec = new CounterCreationData();
            opsPerSec.CounterName = "# requests /sec";
            opsPerSec.CounterHelp = "Number of requests executed per second";
            opsPerSec.CounterType = PerformanceCounterType.RateOfCountsPerSecond32;
            counterCollection.Add(opsPerSec);
            // add a counter tracking operations per second
            CounterCreationData operationTotal = new CounterCreationData();
            operationTotal.CounterName = "Total # requests";
            operationTotal.CounterHelp = "Total number of requests executed";
            operationTotal.CounterType = PerformanceCounterType.NumberOfItems32;
            counterCollection.Add(operationTotal);
            PerformanceCounterCategory.Create(category,
                        "A custom counter category that tracks execution", PerformanceCounterCategoryType.SingleInstance,
                        counterCollection);
        }
        else
        {
            Console.Error.WriteLine("Counter already exists, try specifying parameters for categoryname and or insisting on deleting");
        }
        using (var _totalOperationsCounter = new PerformanceCounter(_category, "Total # requests", false))
        {
            _totalOperationsCounter.ReadOnly = false;
            _totalOperationsCounter.RawValue = 10;
            var count = _totalOperationsCounter.Increment();
        }
    }
}

递增自定义性能计数器.net 4.0 Windows 7

对我来说,行为如下(我不设置RawValue)

  • 当性能监视器未运行时
    • Console.WriteLine(_totalOperationsCounter.Increment())始终显示1
  • 当性能监视器正在运行时
    • 应用程序运行之间的Console.WriteLine(_totalOperationsCounter.Increment())增量