The IDisposable interface is typically implemented by objects that are using resources that need to be released in a timely manner rather than waiting for the garbage collector to clean them up.  Another good use that I’ve come across is using IDisposable to time sections of your code.  In all projects I work on, I typically create a “CodeTimer” class that I can use to time sections of my code for logging or display to the console.  In this post, I’m going to show you how to create a simple utility class that you can use to time sections of code.

Creating the CodeTimer Class

The first thing we need to do is create the CodeTimer class.  This class will need a few things:

  • An object that can calculate how long an operation takes (a Stopwatch will work well here)
  • A constructor that takes some sort of message we can output
  • It will also need to implement IDisposable to output the message when the operation finishes along with the elapsed time

The following class should do the trick:

public class CodeTimer : IDisposable
{
    private Stopwatch _stopwatch = new Stopwatch();
    private string _message = null;

    public CodeTimer(string message)
    {
        _message = message;

        Console.WriteLine(string.Format("Started {0}...", _message));
        _stopwatch.Start();
    }

    public void Dispose()
    {
        _stopwatch.Stop();
        Console.WriteLine(string.Format("{0} took {1} seconds.", _message, _stopwatch.Elapsed.TotalSeconds));
    }
}

This code is pretty simple, so let’s take a step through it.  Notice that we have two private fields.  One is a string called _message and the other is a Stopwatch called _stopwatch.  These two fields will be used throughout the lifetime of the object.

Next, we see there is a constructor that takes a string type.  The string is the message defining the operation that is being timed.  This message is stored in the _message field.  After this, we output a message to the console (you could change this to whatever you like – file, database, etc.) and start up the Stopwatch object.  This begins timing the operation.

Lastly, you’ll see the Dispose method which is part of the IDisposable interface that we have stated we’re implementing in the class definition.  The dispose method simply stops the Stopwatch object and outputs a message containing the amount of seconds since the Stopwatch was started.

That’s it for the CodeTimer class.  The only thing left to do is show how to use this class in other pieces of code.  Take a look at the following code which uses the CodeTimer object:

static void Main(string[] args)
{
    using (new CodeTimer("Sleeping for 5 seconds"))
    {
        Thread.Sleep(TimeSpan.FromSeconds(5));
    }
}

This code should be easy to understand.  We wrap the instantiation of the CodeTimer in a using block.  Inside the using block, we perform our operation that we want timed (in this case, simply putting the thread to sleep for 5 seconds).  When the operation is finished, the application will exit the using block and fire the Dispose method on the CodeTimer since the using keyword guarantees that Dispose will be invoked. When Dispose is called, our message and the time it took for our operation to execute is output to the console.

As you can see, this utility class is super simple to understand and it can truly add a great bit of information to logs to help monitor application performance.

Using IDisposable to Create a Simple Code Timer
Tagged on:     

Leave a Reply