Course contentsShow
← C#
Lesson 1750 of 1,90816. Performance and DiagnosticsFree lesson

Measuring Throughput with Custom EventCounters

Students will create domain-specific performance gauges to monitor business-level throughput.

In this lesson, you will learn how to move beyond system-level metrics by implementing custom EventCounters to track business-specific throughput, such as "orders processed per second."

While EventCounters are excellent for monitoring memory or CPU, their true power lies in domain-level telemetry. By creating a custom counter, you can expose internal application events to diagnostic tools like dotnet-counters without introducing heavy logging overhead or external dependencies.

Implementing a Custom Throughput Gauge

To track throughput, you utilize the EventCounter class. Unlike a simple gauge that tracks a point-in-time value, an EventCounter is designed for high-frequency events; it automatically calculates averages and rates over a time interval.

You typically define a static source to ensure your counter is registered once globally:

using System.Diagnostics.Tracing;

[EventSource(Name = "MyCompany.BusinessMetrics")]
public sealed class OrderMetrics : EventSource
{
    public static readonly OrderMetrics Log = new OrderMetrics();
    private readonly EventCounter _orderCounter;

    private OrderMetrics()
    {
        _orderCounter = new EventCounter("orders-per-second", this);
    }

    public void TrackOrder()
    {
        // Increment the counter by 1 for every order processed
        _orderCounter.WriteMetric(1);
    }
}

Why this matters for throughput

When you call TrackOrder() inside your business logic, you are sending a lightweight signal to the .NET runtime’s diagnostic pipeline. Because EventCounters are "pull-based," they remain dormant until a diagnostic tool (like dotnet-counters or Azure Application Insights) requests the data. This means you can keep high-frequency instrumentation in your production code with negligible performance impact.

By observing the mean and rate reported by this counter, you gain immediate visibility into whether your throughput is scaling linearly with load or if bottlenecks are emerging in your processing pipeline. This data is far more actionable for performance tuning than generic GC or CPU metrics, as it bridges the gap between raw hardware usage and actual business value delivery.

Key Takeaway: Custom EventCounters allow you to surface domain-specific throughput as a first-class diagnostic metric, enabling high-performance monitoring of business logic without the overhead of traditional logging.