Search code examples
c#.netperfmon

Where are my Performance Counter? It is created but I can't see it in perfmon


I have this piece of code : Where I create my Performance Counter. It executes ok, if not exists it creates the performance counter as well, but I can't find this performance counter, when I use perfmon.

What is happening?

 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);
    }

Solution

  • The reason for not receiving any exceptions is try-catch block is missing. If you add your statements in try and catch block like this

            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
            }   
    

    Then it will capture the exceptions.If you see exception like "Requested registry access is not allowed." then you require administrative rights to do the stuff. To confirm this Run the Visual Studio with Administrative rights and execute the code.