在.NET 4.0和Windows 7中增加自定义性能计数器

3

我在Windows 7上增加自定义性能计数器时遇到了一些麻烦。已创建类别和计数器,但调用“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();
        }
    }
}
1个回答

1

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接