Performance Counters ใน C# ใช้สำหรับวัดและติดตามประสิทธิภาพของแอปพลิเคชัน เช่น CPU, Memory, Disk I/O, Network หรือ Custom Counters ของแอปเอง ใช้คลาส PerformanceCounter ในเนมสเปซ System.Diagnostics
การเข้าถึง Performance Counter Categories
using System.Diagnostics;
// ดึงทุก Category
var categories = PerformanceCounterCategory.GetCategories();
// ดึง Category เฉพาะ "Processor"
var processorCategory = PerformanceCounterCategory.GetCategories()
.FirstOrDefault(c => c.CategoryName == "Processor");
สร้างและอ่าน Counter
// อ่าน % Processor Time
using (var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"))
{
float cpuUsage = cpuCounter.NextValue();
// เรียก NextValue() อีกครั้งเพื่อได้ค่าจริง (ครั้งแรกมักเป็น 0)
System.Threading.Thread.Sleep(1000);
cpuUsage = cpuCounter.NextValue();
Console.WriteLine($"CPU Usage: {cpuUsage}%");
}
สร้าง Custom Performance Counter
// ต้องรันเป็น Administrator
if (!PerformanceCounterCategory.Exists("MyApp"))
{
CounterCreationDataCollection counters = new CounterCreationDataCollection();
counters.Add(new CounterCreationData("RequestsPerSec", "Requests per second", PerformanceCounterType.RateOfCountsPerSecond32));
counters.Add(new CounterCreationData("AvgResponseTime", "Average response time (ms)", PerformanceCounterType.AverageTimer32));
PerformanceCounterCategory.Create("MyApp", "My Application Counters", PerformanceCounterCategoryType.SingleInstance, counters);
}
ประเภท Counter หลัก
NumberOfItems32/64- นับจำนวนRateOfCountsPerSecond32- อัตราต่อวินาทีAverageTimer32- เวลาเฉลี่ยSampleFraction- เปอร์เซ็นต์
หมายเหตุ: ใน .NET Core / .NET 5+ บน Linux/macOS ใช้ EventCounter และ dotnet-counters แทน เนื่องจาก PerformanceCounter เป็น Windows-only