Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramonsmits/6fca2172074b4cd66dd511bfcc562981 to your computer and use it in GitHub Desktop.
Save ramonsmits/6fca2172074b4cd66dd511bfcc562981 to your computer and use it in GitHub Desktop.
NServiceBus Machine Latency Windows Performance Counter Sample
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading.Tasks;
using NServiceBus;
using NServiceBus.Pipeline;
class OriginatingMachineLatencyBehavior : Behavior<IIncomingPhysicalMessageContext>
{
ConcurrentDictionary<string, (PerformanceCounter Counter, PerformanceCounter Base)> machineCounters = new ConcurrentDictionary<string, (PerformanceCounter,PerformanceCounter)>();
const string Category = "NServiceBus Machine Latency Sample";
const string LatencyDurationKey = "Latency Duration";
const string LatencyDurationBaseKey = LatencyDurationKey + "Base";
public OriginatingMachineLatencyBehavior()
{
if (PerformanceCounterCategory.Exists(Category))
{
return;
}
var counterCreationDataCollection = new CounterCreationDataCollection
{
new CounterCreationData(LatencyDurationKey, "Time between sending and fetching the message. Requires all system clocks to be synchronized!", PerformanceCounterType.AverageTimer32),
new CounterCreationData(LatencyDurationBaseKey, string.Empty, PerformanceCounterType.AverageBase)
};
PerformanceCounterCategory.Create(Category, "Sample showing how to monitor the time between sending and fetching a message just before invoking the handlers (excluding processing time).", PerformanceCounterCategoryType.MultiInstance, counterCreationDataCollection);
}
public override Task Invoke(IIncomingPhysicalMessageContext context, Func<Task> next)
{
var headers = context.MessageHeaders;
var originatingMachine = headers[Headers.OriginatingMachine];
var timeSent = DateTimeExtensions.ToUtcDateTime(headers[Headers.TimeSent]);
var counter = machineCounters.GetOrAdd(originatingMachine, k => (new PerformanceCounter(Category, LatencyDurationKey, originatingMachine, false),new PerformanceCounter(Category, LatencyDurationBaseKey, originatingMachine, false)));
var duration = DateTime.UtcNow - timeSent;
var performanceCounterTicks = duration.Ticks * Stopwatch.Frequency / TimeSpan.TicksPerSecond;
counter.Counter.IncrementBy(duration.Ticks);
counter.Base.Increment();
return next();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment