Getting accurate ticks from a timer in C#,
I’m trying to rebuild an old metronome application that was originally written using MFC in C++ to be written in .NET using C#. One of the issues I’m running into is getting the timer to “tick” accurately enough.
For example, assuming an easy BPM (beats per minute) of 120, the timer should tick every .5 seconds (or 500 milliseconds). Using this as the basis for the ticks, however, isn’t entirely accurate as .NET only guarantees that your timer will not tick before the elapsed time has passed.
Currently, to get around this for the same 120 BPM example used above, I am setting the ticks to something like 100 milliseconds and only playing the click sound on every 5th timer tick. This does improve the accuracy quite a bit, but if feels like a bit of a hack.
So, what is the best way to get accurate ticks? I know there are more timers available than the windows forms timer that is readily available in Visual Studio, but I’m not really familiar with them.
There are three timer classes called ‘Timer’ in .NET. It sounds like you’re using the Windows Forms one, but actually you might find the System.Threading.Timer class more useful – but be careful because it calls back on a pool thread, so you can’t directly interact with your form from the callback.
Another approach might be to p/invoke to the Win32 multimedia timers – timeGetTime, timeSetPeriod, etc.
A quick google found this, which might be useful
‘Multimedia’ (timer) is the buzz-word to search for in this context.
That’s the answer Getting accurate ticks from a timer in C#, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.
The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you