I have some code that does a lot of work. It does enough work over enough time that we don't generally care about precise accuracy (i.e. to the millisecond), but being off by more than a minute would not be useful. We have a stored procedure that we call to log the start of a task, and the end of the task. Right now we have a lot of code that looks like this:
Logger.LogTaskStart(taskName);
// do stuff
Logger.LogTaskEnd(taskName);
Where the two methods save the metadata, which is eventually persisted via the afore-mentioned stored procedure. We also have some places where we may sometimes log timing information, but not always b/c it is either too much noise, or it usually doesn't have a problem.
if (debug) Logger.LogTaskStart(taskName);
// do stuff
if (debug) Logger.LogTaskEnd(taskName);
We've had issues where we inadvertently mismatch a start & end, or we only put one under a debug flag, etc. We've considered creating a pretty simple logger class that implements IDisposable to do it for us, such that we'd just do this (assume that the constructor starts the timer RAII style, and that Dispose stops it)
using (new Logger(taskName, debug))
{
// Do stuff
}
As best as we can tell, this should just compile to approximately this:
Logger loggerThing = null;
try
{
loggerThing = new Logger(taskName, debug);
// Do stuff
}
finally
{
loggerThing?.Dispose();
}
As such, it seems reasonably safe to use this for our larger tasks with enough granularity to be able to say "that ran a reasonable amount of time" or "that ran substantially faster/slower than normal". Are we right?
From some reading, I found the following articles, code samples, and SO Q&A. We clearly aren't the only people to have thought of this or something similar, but no-one seems to have ever given a clear and definitive answer to the question of "how timely can we assume Dispose will be called, and how reliable would timing results of that be?" Given the first post below, regarding how using
is just syntactic sugar, we're inclined to think that is the case.
- using statement on IDisposable object - delay of calling Dispose method
- Using IDisposable to Create a Simple Code Timer
- .NET Stopwatch meet IDisposable
- Stopwatch used with idisposable, usefull
- Wrapping StopWatch timing with a delegate or lambda?
- PerformanceStopwatch
- Should I Stop Stopwatch at the end of the method?