Course contentsShow
← C#
Lesson 549 of 1,9085. The .NET Runtime and BCL ConceptsFree lesson

Runtime Event Tracing

Capture low-level events for performance debugging using ETW.

In this lesson, you will learn how to tap into the "black box" of the .NET Runtime to capture low-level performance events using Event Tracing for Windows (ETW).

Understanding the Runtime's "Heartbeat"

When your C# application runs, the .NET Runtime is constantly performing background tasks like Garbage Collection (GC) cycles, JIT compilation, and assembly loading. Sometimes, your application might stutter or slow down, but since these actions happen "under the hood," they are invisible to standard debuggers.

ETW is a kernel-level tracing facility that allows the runtime to broadcast high-speed "events" about what it is doing. Think of these as a flight recorder for your application. By capturing these, you can see exactly when a garbage collection triggered or why a thread was blocked, allowing you to correlate performance dips with specific runtime behaviors.

Capturing Events with EventListener

In modern .NET, the easiest way to tap into these streams is by using the System.Diagnostics.Tracing.EventListener class. You can create a listener that subscribes to specific "EventSources" provided by the runtime.

using System.Diagnostics.Tracing;

public class MyPerformanceListener : EventListener
{
    protected override void OnEventWritten(EventWrittenEventArgs eventData)
    {
        // This method triggers every time the runtime fires an event
        Console.WriteLine($"Event: {eventData.EventName} - Time: {DateTime.Now}");
    }
}

By initializing new MyPerformanceListener(), your application begins receiving real-time telemetry. You can filter these events to focus only on what you care about, such as Microsoft-Windows-DotNETRuntime events, which detail GC heap allocations or assembly loading metadata.

Why use ETW over standard logs?

Unlike standard file logging, which can slow your application down significantly, ETW is designed for high-performance scenarios. Because it operates at the kernel level with minimal overhead, it is the industry standard for debugging production-grade performance issues without introducing "observer effect" errors—where the act of measuring the performance actually changes the results.

Key Takeaway: Runtime Event Tracing allows you to hook into low-level system telemetry, providing a non-invasive way to diagnose performance bottlenecks like excessive garbage collection or slow assembly loading.