How to measure elapsed time using DateTime class?
Don't use DateTime
for measuring time intervals.
Use Stopwatch
class, which was designed exactly for this purpose
var clock = new Stopwatch();
clock.Start();
do
{
// do something
}
while (clock.ElapsedMilliseconds < 10000)
clock.Stop();
Note: Of course you can use DateTime
for measuring time, but if you need precision less then second then Stopwatch
is right tool for the job.
And Stopwatch
have much more readable and easy to use methods for measuring time
In your particular case: "wait for at-least ten seconds from program start, before executing task2" you can use asynchronous approach
var task1 = StartTask1();
await Task.Delay(10000); // next line will be executed approximately after 10 s
var task2 = StartTask2();
Your problem is that you measure the milliseconds part of the TimeSpan
. You have to use TotalMilliseconds
instead of Milliseconds
:
do
{
Thread.Sleep(100);
interval = (DateTime.Now - startTime).TotalMilliseconds;
} while (interval < 10000); //wait for at-least ten seconds from program start, before executing task2
With TimeSpan
you always have to use the Total
properties if you want to know the total time that has passed. All properties without Total
in front of them only display the current amount of time that has passed.
For example: A method runs for 1 minute and 7 seconds.
Console.WriteLine(ts.Seconds);
Output:
7
Why is that? Because there are only 60 seconds in a minute and ts.Seconds
will start increasing again from 0 to 59.
Compare this to
Console.WriteLine(ts.TotalSeconds),
Output:
67
Now we have the total amount of seconds that have passed, in this case 67 seconds.