Home > Back-end >  Get elapsed time on a timer
Get elapsed time on a timer

Time:10-11

There was at least one question like that, and answer was "Just use stopwatch". Which I would gladly do, except Stopwatch locks UI, so I'm forced to use Timer. But I can't figure out how to get elapsed time. I have to display it on UI.

The problem: wait X seconds and do something, and display elapsed time.

Timers, easy but can't get elapsed tine:

Timer timer = new Timer
            {
                Interval = 8000 //8 seconds
            };

timer.Enabled = true;
timer.Elapsed  = DoSomething;

Stopwatch, not really pleasant code which blocks UI, but can easily get elapsed time with Elapsed:

            Stopwatch st = new Stopwatch();
            st.Start();
            do
            {
               //wait 8 seconds
            } while (st.ElapsedMilliseconds < 8000);
            DoSomething2();

Basically both things won't do what I really want. And I'm sure there is a way to achieve what I need.

CodePudding user response:

wait X seconds and do something, and display elapsed time

These are two separate goals. A timer is suitable to do the first one, but one might also use something like await Task.Delay(...) that uses a timer internally.

For the second goal you can either assume the timer did actually elapse a the correct time, or measure the actual time yourself using a stopwatch. But the measurement of time is separate from the waiting part. For example

var waitTime = TimeSpan.FromSeconds(8)
var startTime = DateTime.Now;
var stopwatch = Stopwatch.StartNew();
await Task.Delay(waitTime);
// Use waitTime for a rough estimation of the passed time
// (DateTime.Now - startTime ) for a measurement accurate to the system clock, often about 16ms
// stopwatch.Elapsed for an accurate measurement to the tick-frequency (usually much better than a microsecond)
  • Related