From 073c231ef1813fd3b4bab0ea14b9e8d4754a843d Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Wed, 18 Jul 2018 21:34:51 -0400 Subject: [PATCH] feat: Util methods for profiling event subscribers --- ICD.Common.Utils/Timers/IcdStopwatch.cs | 52 +++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/ICD.Common.Utils/Timers/IcdStopwatch.cs b/ICD.Common.Utils/Timers/IcdStopwatch.cs index c930671..bd68176 100644 --- a/ICD.Common.Utils/Timers/IcdStopwatch.cs +++ b/ICD.Common.Utils/Timers/IcdStopwatch.cs @@ -146,6 +146,58 @@ namespace ICD.Common.Utils.Timers } } + /// + /// Executes the event handler and profiles each of the attached subscribers. + /// + /// + /// + /// + public static void Profile(EventHandler eventHandler, object sender, string name) + { + if (eventHandler == null) + { + PrintProfile(new IcdStopwatch(), string.Format("{0} - No invocations", name)); + return; + } + +// ReSharper disable PossibleInvalidCastExceptionInForeachLoop + foreach (EventHandler subscriber in eventHandler.GetInvocationList()) +// ReSharper restore PossibleInvalidCastExceptionInForeachLoop + { + string subscriberName = string.Format("{0} - {1}", name, subscriber.Target.GetType().Name); + + EventHandler subscriber1 = subscriber; + Profile(() => subscriber1(sender, EventArgs.Empty), subscriberName); + } + } + + /// + /// Executes the event handler and profiles each of the attached subscribers. + /// + /// + /// + /// + /// + public static void Profile(EventHandler eventHandler, object sender, T eventArgs, string name) + where T : EventArgs + { + if (eventHandler == null) + { + PrintProfile(new IcdStopwatch(), string.Format("{0} - No invocations", name)); + return; + } + +// ReSharper disable PossibleInvalidCastExceptionInForeachLoop + foreach (EventHandler subscriber in eventHandler.GetInvocationList()) +// ReSharper restore PossibleInvalidCastExceptionInForeachLoop + { + string subscriberName = string.Format("{0} - {1}", name, subscriber.Target.GetType().Name); + + EventHandler subscriber1 = subscriber; + Profile(() => subscriber1(sender, eventArgs), subscriberName); + } + } + private static void PrintProfile(IcdStopwatch stopwatch, string name) { long elapsed = stopwatch.ElapsedMilliseconds;