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(); 
5
  • 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. Commented Feb 3, 2019 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. Commented Feb 3, 2019 at 22:19
  • thanks, I was digging through ecma-international.org/publications/files/ECMA-ST/ECMA-334.pdf and losing hope on solving the second part. Commented Feb 3, 2019 at 22:22
  • Regarding the first part you can create a helper method eg pastebin.com/rRrWEjh6 Commented Feb 3, 2019 at 22:27
  • ok, that works. Thanks :) Commented Feb 3, 2019 at 22:38

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.