O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

(In)appropriate Use of IDisposable

One danger of telling people the implementation of the using statement is that they start to retrofit the pattern for purposes other than deterministic resource cleanup. In its true essence, the using statement is a try-finally statement in disguise with some method call happening nearly at the very end of the associated block. The following is a sample use of IDisposable to implement a code execution timing facility:

using (new ExecutionTimer(Console.Out /* to log to */))    // Code to be benchmarked goes here.

Here, the constructor of ExecutionTimer starts the timer, and the Dispose method stops it, printing the elapsed time since the constructor was called to the specified logger. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required