1
votes

I am doing a simple high score add-in for a game. For this, I need a precise timer from which I can display the elapsed time in a Label. I have so far tried the following:

Windows.Forms.Timer: does not keep high resolution intervals, some are slower, some are faster.

System.Diagnostics.Stopwatch: no tick event.

I also thought of implementing a low-resolution Forms.Timer. Then, when the timer starts and stops I would store the system time and just subtract them to get the elapsed time. But I don't want to over-complicate things. Any ideas?

3
So you want to display the number of ticks elapsed in the label? - System Down
What are you trying to do exactly – measure elapsed time or execute code in intervals? - dtb
An event can never be precise in time - it is processed in the message loop with no guarantee about when it happens. Why does the event need to be precise? Why does the stopwatch need a tick event? - J...
@J...I wanted to store the exact time needed to complete a game. And I need to display the elapsed time in a label - LeonidasFett
A Timer has plenty of resolution to assign the label's Text property. It just turns into a blur to human eyes when you do it faster than 25 times per second. The actual value that you display doesn't have anything to do with that timer. Stopwatch is fine for that. - Hans Passant

3 Answers

3
votes

I don't think it would be overcomplicated to use a combination of a Stopwatch (for its high resolution) and the low-resolution Windows.Forms.Timer.

The Stopwatch is extremely straightforward to use, so it adds very little complexity to using a Timer too.

(This assumes you are ok with high-resolution elapsed time display but with a lower-resolution update interval.)

3
votes

Use elapsed time since some moment. Than either:

  • Pick any timer, set it for 15ms and display elapsed time on each tick (should be ok if you are dealing with WinForm/WPF controls)
  • On every frame refresh display new value (if your code get notified/invoked on every frame refresh)
0
votes

If you're willing to take the dependency, you could use Reactive Extensions (Rx) to get a timer:

var timer = Observable.Interval(TimeSpan.FromMilliseconds(15))
            .Subscribe(() => /* handler */ );

Rx will make sure that the handler is called on the same thread the subscription was created on, and under the covers it uses System.Threading.Timer so it has pretty high and consistent resolution.