0

I'm creating some extension methods to help gather metrics on anonymous functions in my code. unfortunately, they tend to have some code duplication and I'm unsure how to remove it.

    public static Action Instrument(this Action a, [CallerMemberName] string caller = null)
    => () =>
    {
        var sw = Stopwatch.StartNew();
        try
        {
            a();
        }
        finally
        {
            Trace.WriteLine($"{caller} : {sw.ElapsedMilliseconds} ms");
        }
    };

    public static Action<T> Instrument<T>(this Action<T> a, [CallerMemberName] string caller = null)
    => (t) =>
    {
        var sw = Stopwatch.StartNew();
        try
        {
            a(t);
        }
        finally
        {
            Trace.WriteLine($"{caller} : {sw.ElapsedMilliseconds} ms");
        }
    };

having 4 of these for actions and 4 for functions means that my try{ } finally{ } gets duplicated way too often. How do I re-write this to prevent the duplication?

Also is there a way to inline the first 2 lines of this

Action a = () => { Thread.Sleep(100); }; 
a = a.Instrument();
a();
Bas Hamer
  • 304
  • 3
  • 16
  • That is mostly stopwatch syntax, none really address the generic syntax; I'd like to be able to chain more methods together in a fluent API fashion; the stopwatch is just an example. – Bas Hamer Feb 03 '19 at 22:08
  • I was about to write an answer, however the question was unfortunately closed. Anyway regarding the 2nd part, of course you can: `(new Action(() => Thread.Sleep(100)).Instrument())();` The first part will not fit in the comment. – Dzienny Feb 03 '19 at 22:19
  • thanks, I was digging through https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-334.pdf and losing hope on solving the second part. – Bas Hamer Feb 03 '19 at 22:22
  • Regarding the first part you can create a helper method eg https://pastebin.com/rRrWEjh6 – Dzienny Feb 03 '19 at 22:27
  • ok, that works. Thanks :) – Bas Hamer Feb 03 '19 at 22:38

0 Answers0