7

我有这段代码:我在哪里创建我的性能计数器。它执行正常,如果不存在,它也会创建性能计数器,但是当我使用 perfmon 时找不到这个性能计数器。

怎么了?

 const string _categoryName = "MyPerformanceCounter";
    if (!PerformanceCounterCategory.Exists(_categoryName))
    {
        CounterCreationDataCollection counters = new CounterCreationDataCollection();

        CounterCreationData ccdWorkingThreads = new CounterCreationData();
        ccdWorkingThreads.CounterName = "# working threads";
        ccdWorkingThreads.CounterHelp = "Total number of operations executed";
        ccdWorkingThreads.CounterType = PerformanceCounterType.NumberOfItems32;
        counters.Add(ccdWorkingThreads);

        // create new category with the counters above
        PerformanceCounterCategory.Create(_categoryName,
                "Performance counters of my app",
                PerformanceCounterCategoryType.SingleInstance,
                counters);
    }
4

2 回答 2

2

没有收到任何异常的原因是缺少 try-catch 块。如果您像这样在 try 和 catch 块中添加语句

        try
        {                
            const string _categoryName = "MyPerformanceCounter";
            if (!PerformanceCounterCategory.Exists(_categoryName))
            {
                CounterCreationDataCollection counters = 
                new CounterCreationDataCollection();

                CounterCreationData ccdWorkingThreads = new CounterCreationData();
                ccdWorkingThreads.CounterName = "# working threads";
                ccdWorkingThreads.CounterHelp = "Total number of operations executed";
                ccdWorkingThreads.CounterType = PerformanceCounterType.NumberOfItems32;
                counters.Add(ccdWorkingThreads);

                // create new category with the counters above
                PerformanceCounterCategory.Create(_categoryName,
                        "Performance counters of my app",
                        PerformanceCounterCategoryType.SingleInstance,
                        counters);
            }                
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString()); //Do necessary action
        }   

然后它将捕获异常。如果您看到“不允许请求的注册表访问”之类的异常。那么你需要管理权限来做这些事情。要确认这一点,使用管理权限运行 Visual Studio 并执行代码。

于 2012-10-01T11:11:47.047 回答
1

除了以管理员身份运行 Visual Studio 以允许创建类别之外,我遇到了同样的问题 - .NET 代码报告计数器在那里,但在 perfmon 中没有可见的此类计数器类别。

显然 perfmon 有时会通过在注册表中将其标记为禁用来禁用性能计数器

如果您在注册表中检查,HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services应该能够找到您的性能计数器类别(只需将您的类别名称作为“文件夹”之一查找)。在子项(“文件夹”)下Performance找到注册表值Disable Performance Counters并将其设置为零。重新启动 perfmon,您现在应该在 perfmon 中看到您的类别和计数器。

于 2014-10-09T14:26:53.057 回答