I'm new to programming. I'm trying to evaluate time in milliseconds using System.Timer
, to break out of a while
loop when current time
matches the past time + a number of milliseconds
(which meets the future condition).
Sometimes it exits the loop successfully but other times it runs as an infinite loop. I am thinking that it has something to do with the milliseconds clock precision, but I'm not sure. A Console output of the variables shows timeFuture
to be correct.
I've looked at Timespan
but not sure how to use that. Many thanks for any feedback.
long end = 500; //500 milliseconds
long timeStart = DateTime.Now.Millisecond; //time in milliseconds
long timeFuture = timeStart + end;
long timeNow = 0;
while (true)
{
timeNow = DateTime.Now.Millisecond;
if (timeFuture - timeNow == 0) { break; }
Console.WriteLine(timeNow);
}
DateTime.Now.Milisecond
doesn't return the time in miliseconds, but the actual milisecond at the point in time that the DateTime
instance represents (so it will always be between 0 and 999). Additionally, as you are running on a multi-threaded system, your condition might never be executed at the exact point in time when it would evaluate to true
(writing to the console consumes time as well).
So you might consider changing your condition and make use of the Timespan
class:
DateTime timeStart = DateTime.Now;
while (true)
{
DateTime timeNow = DateTime.Now;
TimeSpan difference = (timeNow - timeStart);
if (difference.TotalMilliseconds >= 500) { break; }
Console.WriteLine(timeNow);
}
Millisecond is the component of the time, not a time span. You want something like
DateTime start = DateTime.Now;
while (true)
{
if ((DateTime.Now - start ).TotalMilliseconds>500) // Is a timespan
{ break; }
Console.WriteLine(timeNow);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.