Created
January 17, 2024 16:45
-
-
Save ReubenBond/12bf2a03a953845fe0bdb645d87c41d4 to your computer and use it in GitHub Desktop.
.NET CPU Usage EventCounter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Diagnostics.Tracing; | |
using System.Security.Cryptography; | |
using System.Text; | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var listener = new SystemRuntimeEventCounterListener(); | |
Task.Run(async () => | |
{ | |
while (true) | |
{ | |
await Task.Delay(1000); | |
_ = Task.Run(() => | |
{ | |
for (var i = 0; i < 1_000_000; ++i) | |
{ | |
SHA512.HashData(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())); | |
}; | |
}); | |
} | |
}); | |
Console.WriteLine("Press any key to exit"); | |
Console.ReadKey(); | |
} | |
} | |
internal sealed class SystemRuntimeEventCounterListener : EventListener | |
{ | |
protected override void OnEventSourceCreated(EventSource source) | |
{ | |
if (source.Name.Equals("System.Runtime")) | |
{ | |
Dictionary<string, string?>? refreshInterval = new() { ["EventCounterIntervalSec"] = "0.5" }; | |
EnableEvents(source, EventLevel.Informational, (EventKeywords)(-1), refreshInterval); | |
} | |
} | |
public double CpuUsage { get; private set; } | |
protected override void OnEventWritten(EventWrittenEventArgs eventData) | |
{ | |
if (eventData.EventName!.Equals("EventCounters")) | |
{ | |
for (int i = 0; i < eventData.Payload!.Count; i++) | |
{ | |
if (eventData.Payload![i] is IDictionary<string, object> eventPayload) | |
{ | |
if (eventPayload.TryGetValue("Name", out var name) && "cpu-usage".Equals(name)) | |
{ | |
if (eventPayload.TryGetValue("Mean", out var mean)) | |
{ | |
CpuUsage = (double)mean; | |
Console.WriteLine($"cpu-usage: {CpuUsage}"); | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment