当前位置:首页 > C# > 正文

C#性能计数器详解(手把手教你使用PerformanceCounter监控系统资源)

在开发 C# 应用程序时,我们常常需要了解程序运行时的性能表现,比如 CPU 使用率、内存占用、磁盘读写速度等。这时候,C#性能计数器(PerformanceCounter)就派上用场了!它是 .NET Framework 提供的一个强大工具,能够帮助开发者实时监控系统和应用程序的性能指标。

C#性能计数器详解(手把手教你使用PerformanceCounter监控系统资源) C#性能计数器 PerformanceCounter教程 .NET性能监控 C#系统监控 第1张

什么是 PerformanceCounter?

PerformanceCounter 是 .NET 中 System.Diagnostics 命名空间下的一个类,它允许你读取 Windows 性能监视器(Performance Monitor)中提供的各种性能数据。这些数据包括但不限于:

  • CPU 使用率(% Processor Time)
  • 可用物理内存(Available MBytes)
  • 磁盘读写速度(Disk Reads/sec)
  • 网络接口流量(Bytes Total/sec)
  • 自定义应用程序计数器(如每秒处理请求数)

通过使用 .NET性能监控 功能,你可以轻松构建自己的性能仪表盘或日志系统,这对排查性能瓶颈非常有帮助。

如何使用 PerformanceCounter?

下面是一个简单的示例,展示如何使用 C# 读取当前系统的 CPU 使用率:

using System;using System.Diagnostics;class Program{    static void Main()    {        // 创建一个 PerformanceCounter 实例        using (var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"))        {            // 第一次调用 NextValue() 通常返回 0,需等待后再调用            cpuCounter.NextValue();            System.Threading.Thread.Sleep(1000);            float cpuUsage = cpuCounter.NextValue();            Console.WriteLine($"当前 CPU 使用率: {cpuUsage:F2}%");        }    }}

上面代码中,我们指定了三个参数:

  1. CategoryName:性能计数器类别,如 "Processor"(处理器)
  2. CounterName:具体计数器名称,如 "% Processor Time"(处理器时间百分比)
  3. InstanceName:实例名称,"_Total" 表示所有 CPU 核心的总和

常见性能计数器类别与名称

以下是一些常用的 C#系统监控 计数器组合:

类别(Category) 计数器(Counter) 说明
Memory Available MBytes 可用物理内存(MB)
PhysicalDisk Disk Reads/sec 每秒磁盘读取次数
Network Interface Bytes Total/sec 网络总吞吐量(字节/秒)

创建自定义性能计数器(高级)

除了读取系统内置的计数器,你还可以为自己的应用程序创建自定义性能计数器。例如,监控 Web API 每秒处理的请求数:

// 注意:创建自定义计数器需要管理员权限if (!PerformanceCounterCategory.Exists("MyAppStats")){    var counterData = new CounterCreationDataCollection();    var requestsPerSec = new CounterCreationData    {        CounterName = "Requests/Sec",        CounterHelp = "每秒处理的请求数",        CounterType = PerformanceCounterType.RateOfCountsPerSecond32    };    counterData.Add(requestsPerSec);    PerformanceCounterCategory.Create(        "MyAppStats",        "我的应用程序性能统计",        PerformanceCounterCategoryType.SingleInstance,        counterData);}// 使用自定义计数器using (var counter = new PerformanceCounter("MyAppStats", "Requests/Sec", readOnly: false)){    counter.Increment(); // 每处理一个请求就调用一次}
注意: 创建自定义计数器需要以管理员身份运行程序,并且只能创建一次。重复创建会抛出异常。

总结

通过本文,你应该已经掌握了如何使用 PerformanceCounter教程 中的核心知识点。无论是监控系统资源还是构建自定义性能指标,PerformanceCounter 都是一个强大而灵活的工具。合理利用它,可以显著提升你的 C# 应用程序的可观测性和稳定性。

记住,在实际项目中,建议将性能监控逻辑封装成服务,并定期采样记录,避免频繁调用影响主程序性能。

希望这篇关于 C#性能计数器 的入门教程对你有所帮助!如果你有任何问题,欢迎在评论区留言交流。