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

时间:2011-06-02 20:40:27

标签: c# .net c#-4.0 .net-4.0 performancecounter

我在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 个答案:

答案 0 :(得分:1)

对我而言,行为如下(我没有设置RawValue)

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