(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. ...