0

I have this method:

    internal async Task PausingForPeriodOftimeAsync() {
        var sw = new Stopwatch();
        sw.Start();
        Console.WriteLine( $"1. - async: Running for {sw.Elapsed.Milliseconds} ms");
        Console.WriteLine( $"1. - async: Time: {DateTime.Now.ToLongTimeString()}");
        await Task.Delay(5000);
        Console.WriteLine($"2. - async: Running for {sw.Elapsed.Milliseconds} ms");
        Console.WriteLine($"2. - async: Time: {DateTime.Now.ToLongTimeString()}");
    }

The result on screen:

1.- async: Running for 0 ms

1.- async: Time: 11:07:30

2.- async: Running for 7 ms

1.- async: Time: 11:07:35

I don't understand why the timer only ran for 5 milliseconds while DateTime shows (rightly) the time five seconds later. How is it possible?

Ajith
  • 1,447
  • 2
  • 17
  • 31

1 Answers1

1

By using sw.Elapsed.Milliseconds you are getting the milliseconds part of the elapsed time. If you want to get the whole elapsed time consider using sw.Elapsed.TotalMilliseconds.