Skip to main content
 首页 » 编程设计

c#之性能计数器不显示

2024年02月13日11Renyi-Fan

我有这个程序。运行此程序后,我尝试查看 perfmon.exe 中的计数器,但性能监视器中的计数器没有变化。

我正在运行带有最新 .NET 的 Win 8.1,并以管理员身份运行 Visual Studio。

class Program 
{ 
    static void Main(string[] args) 
    { 
        if (CreatePerformanceCounters()) 
        { 
            Console.WriteLine("Created performance counters"); 
            Console.WriteLine("Please restart application"); 
            Console.ReadKey(); 
            return; 
        } 
        var totalOperationsCounter = new PerformanceCounter("MyCategory", "# operations executed", "", false); 
        var operationsPerSecondCounter = new PerformanceCounter("MyCategory", "# operations / sec", "", false); 
        totalOperationsCounter.Increment(); 
        operationsPerSecondCounter.Increment(); 
    } 
    private static bool CreatePerformanceCounters() 
    { 
        if (!PerformanceCounterCategory.Exists("MyCategory")) 
        { 
            CounterCreationDataCollection counters = new CounterCreationDataCollection  
            {  
                new CounterCreationData("# operations executed", "Total number of operations executed", PerformanceCounterType.NumberOfItems32),  
                new CounterCreationData("# operations / sec", "Number of operations executed per second", PerformanceCounterType.RateOfCountsPerSecond32) 
            }; 
            PerformanceCounterCategory.Create("MyCategory", "Sample category for Codeproject", counters); 
            return true; 
        } 
        return false; 
    } 
} 

请您参考如下方法:

您的应用在写入计数器后立即退出。尝试让进程保持更长的时间,您将在 perfmon 中看到计数器。