Geeks With Blogs


INauseous() Shawn Cicoria - Solution Architect, Craftsman and Artisan - INauseous() - Main Blog Here:

I wanted an ability to be able to simply time methods and write to a log/trace sink and a very simple approach that I ended up using was to provide a method that takes an Action delegate which would be the method that is to be timed.

The following is what I came up with (this is my reminder…)

class Program
    static void Main(string[] args)

    private static void TestMethod1()
        LoggingHelper.TimeThis("doing something", () =>
            Console.WriteLine("This is the Real Method Body");

public static class LoggingHelper
    public static void TimeThis(string message, Action action)
        string methodUnderTimer = GetMethodCalled(1);
        Stopwatch sw = Stopwatch.StartNew();
        LogMessage( string.Format("started: {0} : {1}", methodUnderTimer, message));
        LogMessage(string.Format("ended  : {0} : {1} : elapsed : {2}", methodUnderTimer, message, sw.Elapsed));


    private static string GetMethodCalled(int stackLevel)
        StackTrace stackTrace = new StackTrace();
        StackFrame stackFrame = stackTrace.GetFrame(stackLevel + 1);
        MethodBase methodBase = stackFrame.GetMethod();
        return methodBase.Name;

    static void LogMessage(string message){
        Console.WriteLine("{0}", message);

Posted on Wednesday, September 21, 2011 3:15 PM .NET | Back to top

Comments on this post: Use an Action delegate to time a method…

Comments are closed.
Comments have been closed on this topic.
Copyright © Shawn Cicoria | Powered by: