Often it is useful to be able to test whether a specific amount of time has passed since an earlier event. This can be handy in scenarios where timeouts are required. It can also be useful in simple micro-benchmarks, when you want to see how many times a particular piece of code can be executed over a given time period.
It's fairly straightforward to do this with the .NET DateTime
and TimeSpan
classes, but such an approach is not robust. This will work most of the time:
// Danger - only useful for throwaway code. DateTime endTime = DateTime.Now + TimeSpan.FromSeconds(5); while (endTime > DateTime.Now) { // Do Work... }
However, if the user changes the clock during this loop, or if the system changes it while synchronizing with a time server, this code won't work.
The Environment.TickCount
property doesn't suffer from this - it increases monotonically
until it wraps round. Unfortunately, the wrapping around makes it slightly awkward to use correctly. (It's not
uncommon for code that depends on TickCount
to be broken for every other 25 days, because
it fails to cope with the 50% of the time that the value is negative.)
This helper class wraps up the necessary boilerplate required to use TickCount
correctly.
It provides a simple usage model:
WaitForTicks wait = new WaitForTicks(TimeSpan.FromSeconds(5)); while (!wait.TimeIsUp) { // Do Work... }
View the source here.