在开发高性能的 C# 应用程序时,了解应用程序运行时的状态至关重要。Windows 提供了强大的 性能计数器(Performance Counters) 机制,帮助开发者实时监控 CPU、内存、磁盘 I/O 等系统资源,甚至可以监控我们自己应用程序的关键指标。本文将详细讲解如何在 C# 中创建和使用自定义性能计数器,即使你是编程新手也能轻松上手!
性能计数器是 Windows 操作系统提供的一种机制,用于收集和报告有关系统或应用程序性能的数据。例如:
通过 perfmon.exe(性能监视器)工具,你可以实时查看这些数据。而使用 C#,我们可以创建属于自己的性能计数器,用于监控业务逻辑中的关键指标。
创建自定义性能计数器需要管理员权限,因为这会向 Windows 注册表写入信息。因此,请确保:
在 C# 中,我们需要先检查是否已存在同名的性能计数器类别,如果不存在则创建它。以下是一个完整的示例:
using System;using System.Diagnostics;public class PerformanceCounterHelper{ private const string CategoryName = "MyApp Metrics"; private const string CounterName = "Requests Per Second"; public static void CreateCounterCategory() { if (!PerformanceCounterCategory.Exists(CategoryName)) { var counterDataCollection = new CounterCreationDataCollection(); var counterData = new CounterCreationData { CounterName = CounterName, CounterHelp = "Number of requests processed per second", CounterType = PerformanceCounterType.RateOfCountsPerSecond32 }; counterDataCollection.Add(counterData); // 创建类别 PerformanceCounterCategory.Create( categoryName: CategoryName, categoryHelp: "Custom counters for MyApp", PerformanceCounterCategoryType.SingleInstance, counterDataCollection ); Console.WriteLine($"Performance counter category '{CategoryName}' created."); } else { Console.WriteLine($"Category '{CategoryName}' already exists."); } }} 这段代码做了以下几件事:
RateOfCountsPerSecond32,表示“每秒事件发生次数”创建好计数器后,就可以在业务逻辑中更新它的值了:
public class RequestProcessor{ private PerformanceCounter _requestCounter; public RequestProcessor() { // 初始化性能计数器(只读模式设为 false 表示可写) _requestCounter = new PerformanceCounter( categoryName: "MyApp Metrics", counterName: "Requests Per Second", instanceName: null, readOnly: false ); } public void ProcessRequest() { // 模拟处理请求 // ... // 增加计数器值 _requestCounter.Increment(); } public void Dispose() { _requestCounter?.Dispose(); }} 每次调用 ProcessRequest() 方法时,计数器就会加 1。Windows 会自动计算每秒的平均值,并在性能监视器中显示。
1. 按下 Win + R,输入 perfmon 并回车,打开性能监视器。
2. 点击绿色加号 “+”,在“可用计数器”列表中找到 “MyApp Metrics”。
3. 添加 “Requests Per Second” 计数器,即可实时看到你的应用程序每秒处理的请求数!
PerformanceCounterCategory.Delete("MyApp Metrics"),同样需要管理员权限。EventCounters 替代传统性能计数器,因其跨平台且开销更低。但在 Windows 环境下,C#性能计数器 仍是强大且直观的选择。PerformanceCounterType,如 AverageCount64、NumberOfItems32 等,务必查阅官方文档。通过本文,你已经学会了如何在 C# 中创建和使用自定义性能计数器。这项技术对于构建可监控、可维护的企业级应用非常有价值。无论是用于调试、性能分析还是生产环境告警,Windows性能计数器 都是你工具箱中的利器。
记住,良好的监控始于清晰的指标定义。现在,就去为你的 .NET 应用添加第一个自定义计数器吧!
关键词回顾:C#性能计数器、自定义性能计数器、.NET性能监控、Windows性能计数器。
本文由主机测评网于2025-12-18发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025129689.html