Category Archives: C#

stopwatch

.NET Stopwatch meet IDisposable

You’re probably aware of the .NET Stopwatch class, a System.Diagnostics class that ‘Provides a set of methods and properties that you can use to accurately measure elapsed time’.

A code sample illustrates its typical usage:

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;

You get the idea – create, start, execute code (thanks Thread.Sleep(…)), stop and examine its Elapsed property.

There are a number of open source profilers such as Prof-It that provide comprehensive timing information, and there can be some discrepancies when timing code execution with a Stopwatch, as this excellent Code Project article explains, it’s often sufficient to temporarily put in a Stopwatch block to time a piece of code.

One thing to note from the code sample is that it is a little verbose.  The Thread.Sleep(…) call is trivial, for our example, but if we’re timing several lines, the various Stopwatch boilerplate lines rather get in the way.

Wouldn’t it be nice if we could write something like this:

using (new CleverTimer()))
{
	Thread.Sleep(10000);
}

We can, with this little ‘CleverTimer’ class, which uses a mix of a Stopwatch and IDisposable:

public class CleverTimer : IDisposable
{
	private readonly Stopwatch _stopwatch;
	private readonly Action<Stopwatch> _action;
	public CleverTimer(Action<Stopwatch> action = null)
	{
		_action = action ?? (s => Console.WriteLine(s.ElapsedMilliseconds));
		_stopwatch = new Stopwatch();
		_stopwatch.Start();
	}
	public void Dispose()
	{
		_stopwatch.Stop();
		_action(_stopwatch);
	}
	public Stopwatch Watch
	{
		get { return _stopwatch; }
	}
}

The class has a couple of members – the all important Stopwatch, as well as an Action of type Stopwatch.  The constructor can accept an Action, but defaults to writing out the Elapsed milliseconds of the stopwatch.   The constructor creates a the member Stopwatch and starts it.

The Dispose method, required for the implementation of the IDisposable interface, simple stops the Stopwatch member and invokes the _action code.

It’s all fairly simple stuff, but goes some way to simplifying timed code.

Book Review – Instant .NET 4.5 Extension Methods How-to

Packt’s ‘Instant’ Series promises short, fast, focused guides delivering immediate results. But does their Instant .NET 4.5 Extension Method How-to incarnation deliver, or leave readers wanting more?

It is indeed a short book – 52 pages, and it’s 25% before the technical content starts.

.NET 4.5 Extension Methods How-to
.NET 4.5 Extension Methods How-to

After a brief general introduction, the book follows a code sample and explanation format. Each item is labelled with a difficulty grading, with ‘must know’, ‘should now’, and ‘become an expert’.

The ‘become an expert’ items go beyond the ‘syntactic sugar’ aspects of extension methods and demonstrate their usage in modern .NET design.

Whilst the book costs just over a fiver here in the UK, I felt that it was a little lacking. I spotted a grammatical and code formatting issue, and the format of code and explanation feels a little rushed. The more advanced areas would have ideally had more explanation as to how extension methods fit into the .NET ecosystem.

Another issue is that the book offers nothing over the wealth of articles freely available on the Internet.

How to create a Custom Debug Visualizer in Visual Studio

In this screencast, I talk through the process of creating a simple custom debug visualizer to view a System.Drawing.Image image.

Essentially, the visualizer is a class library that references the Microsoft.VisualStudio.DebuggerVisualizers and System.Windows.Forms assemblies. The project has a class, ImageVisualizer, that inherits the .NET framework DialogDebuggerVisualizer class, and overrides its Show method:

class ImageVisualizer : DialogDebuggerVisualizer
{
    protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
    {
        Image image = (Image)objectProvider.GetObject();
        ImageForm form = new ImageForm { DebugImage = image };
        windowService.ShowDialog(form);
    }
}

This converts the variable that’s being debugged to an Image type using the objectProvider parameter’s GetObject method call. This is then assigned to the dialog’s DebugImage property, and the dialog is shown using the windowService parameter’s ShowDialog method.

The actual dialog is very simple indeed, comprising of just a PictureBox to show the image, and a close button to, well, close the dialog.

public Image DebugImage
{
    set
    {
        this.pictureBoxImage.Image = value;
        this.pictureBoxImage.SizeMode = PictureBoxSizeMode.Zoom;
    }
    get
    {
        return this.pictureBoxImage.Image;
    }
}

The dialog class’ DebugImage property simply assigns the picture box’s Image property and zooms. I kept things simple for the screencast, but there’s no reason why the dialog couldn’t be extended to show other image properties such as image location, image type, and dimensions.

To use the visualizer, simply build the project and copy the dll to the Visualizers directory, which on my machine is:

C:Program Files (x86)Microsoft Visual Studio 10.0Common7PackagesDebuggerVisualizers

This particular path relates specifically to my machine, since I’m running 64 bit windows, and Visual Studio 10. Once the dll has been copied, it can be used on the next debug session. In the screencast, I use a simple console program example that loads an image from file. Clicking on the magnifying glass opens up the visualizer’s dialog, and the image can be seen.