A pausable clock for C#
DateTimeDebug
is useful for unit-testing code that uses DateTime.Now
.
The only changes required in the tested code are substitutions of DateTime.Now
with DateTimeDebug.Now
.
Unit tests that use DateTimeDebug.Now
are fast
because they simulate the passage of time without actually waiting,
and they are easier to write because they aren't subject to variations
in elapsed time caused by outside influences.
DateTimeDebug
can also make interactive debugging easier.
This use case requires the use of debugger hooks to cause DateTimeDebug
to be paused
while the program being debugged is paused.
Apparently there are no such debugger hooks for C# debugging as of this writing,
but if you're using C# to build a simulation with its own debugger,
your simulation can provide and use its own hooks.
DateTimeDebug
is not a data type; all public
members are static
.
Now
is aDateTime
value, initially identical to the value ofDateTime.Now
, possibly paused, possibly lagging behindDateTime.Now
.- The behavior of
Now
can be influenced by the other properties. - Changing
Now
affectsLag
.
Running
is the running/paused state ofNow
.Running
istrue
by default.- Changing
Running
tofalse
causesNow
to pause and make no further progress. - Changing
Running
totrue
causesNow
to resume, lagging behindDateTime.Now
by the accumulatedLag
caused by pausing.
Lag
is the amount of time thatNow
lags behindDateTime.Now
.Lag
is0
by default.- The behavior of
Lag
can be influenced by the other properties. - Changing
Lag
affectsNow
.
The code:
- DateTimeDebug.cs
- Demo.cs (called by Test.cs and Program.cs)