Can someone explain this behavior?
Yes: It is very unlikely that the elapsed time calculated from DateTime.Now
is exactly equal to your specified TimeSpan
.
From your comments, it seems that you want to periodically check if it's time to do something. One easy way to do this is to use a Stopwatch
to keep track of the amount of time that has elapsed since the last time you did the thing:
using System;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
throttleTimer.Start();
// This loop simulates your periodic check to see if the action
// needs to be performed:
while (true)
{
doActionIfTimeElapsed(TimeSpan.FromSeconds(5));
Thread.Sleep(1000); // Simulate checking every 1 second or so.
}
}
static Stopwatch throttleTimer = new Stopwatch();
static void doActionIfTimeElapsed(TimeSpan period)
{
if (throttleTimer.Elapsed <= period)
return;
doAction();
throttleTimer.Restart();
}
static void doAction()
{
Console.WriteLine("Doing the action.");
}
}
}
This sample program will perform doAction()
whenever you call doActionIfTimeElapsed()
and more than 5 seconds has elapsed since the last time it called doAction()
.
Alternatively, if you want to perform an action after every N seconds without having to call a method to periodically check if the action should be performed, then you can use a System.Threading.Timer
instead.