C# provides a construct that allows the execution of the IDisposable.Dispose() method, at the end of a specific scope.

Umbrella provides an extension that decorates a System.Action (generic or not) in such a way that it will be called when Dispose is called.

For instance, to estimate the execution duration of a method :

    public static void DummyMethod()
    {
        using (TimeMethod())
        {
            Console.WriteLine("I'm in the method...");
            // Do something...
        }

        // The approximate time spent in the using block has been displayed at the end of the using scope.
    }

    public static IDisposable TimeMethod()
    {
        var w = Stopwatch.StartNew();

        Action stopTimer = () => {
           Console.WriteLine(w.Elapsed);
        };

        return stopTimer.ToDisposable();
    }

Such a technique allows the separation of the code that need to be timed, and the code the actually times the execution.

Last edited Feb 24, 2009 at 3:08 AM by jlaban, version 1

Comments

No comments yet.