diff --git a/src/Amazon.CloudWatch.EMF.Web/ApplicationBuilderExtensions.cs b/src/Amazon.CloudWatch.EMF.Web/ApplicationBuilderExtensions.cs index 3e3610a..de08e25 100644 --- a/src/Amazon.CloudWatch.EMF.Web/ApplicationBuilderExtensions.cs +++ b/src/Amazon.CloudWatch.EMF.Web/ApplicationBuilderExtensions.cs @@ -61,8 +61,8 @@ public static void UseEmfMiddleware(this IApplicationBuilder app, Func { - Stopwatch stopWatch = new Stopwatch(); - stopWatch.Start(); + var valueStopwatch = ValueStopwatch.StartNew(); + await next.Invoke(); var config = context.RequestServices.GetRequiredService(); var logger = context.RequestServices.GetRequiredService(); @@ -73,8 +73,9 @@ public static void UseEmfMiddleware(this IApplicationBuilder app, Func _startTimestamp != 0; + + private ValueStopwatch(long startTimestamp) + { + _startTimestamp = startTimestamp; + } + + public static ValueStopwatch StartNew() => new ValueStopwatch(Stopwatch.GetTimestamp()); + + public TimeSpan GetElapsedTime() + { + // Start timestamp can't be zero in an initialized ValueStopwatch. It would have to be literally the first thing executed when the machine boots to be 0. + // So it being 0 is a clear indication of default(ValueStopwatch) + if (!IsActive) + { + throw new InvalidOperationException( + "An uninitialized, or 'default', ValueStopwatch cannot be used to get elapsed time."); + } + + var end = Stopwatch.GetTimestamp(); + + var timestampDelta = end - _startTimestamp; + var ticks = (long)(TimestampToTicks * timestampDelta); + return new TimeSpan(ticks); + } + } +} \ No newline at end of file