I am encountering a strange behavior here. Control never comes out of the do-while loop. On debugging i found that the value of the variable interval decreases during some of the loops, instead of increasing! I'm missing something obvious here, but can't figure it out.
static void Main(string[] args)
{
int interval = 0;
DateTime startTime = DateTime.Now;
//Task1(); //Task1 can take 4-8 seconds to complete
do
{
Thread.Sleep(100);
interval = (DateTime.Now - startTime).Milliseconds;
} while (interval < 10000); //wait for at-least ten seconds from program start, before executing task2
//Task2();
}
currentTimeMillis(); long elapsedTime = end - start; In the example above, we're using the “System. currentTimeMillis()” static method. The method returns a long value, which refers to the number of milliseconds since January 1st, 1970, in UTC.
How do you calculate elapsed time? Calculating elapsed time can be done by measuring the time between the start and finish of an event. This can be done by the use of simple addition or subtraction.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With