Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting accurate ticks from a timer in C#

Tags:

.net

timer

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.

like image 990
jerhinesmith Avatar asked Aug 12 '08 12:08

jerhinesmith


3 Answers

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 http://www.codeproject.com/KB/miscctrl/lescsmultimediatimer.aspx

'Multimedia' (timer) is the buzz-word to search for in this context.

like image 152
Will Dean Avatar answered Nov 08 '22 18:11

Will Dean


What is the C++ application using? You can always use the same thing or wrap the timer code from C++ into a C++/CLI class.

like image 23
Coincoin Avatar answered Nov 08 '22 19:11

Coincoin


I have had this problem when developing a recent data-logging project. The problem with the .NET timers ( windows.forms, system.threading, and system.timer ) is that they are only accurate down to around 10 milli seconds which is due to the event scheduling built into .NET I believe. ( I am talking about .NET 2 here ). This wasn't acceptable for me and so I had to use the multimedia timer ( you need to import the dll ). I also wrote a wrapper class for all the timers and so you can switch between them if necessary using minimal code changes. Check out my blog post here: http://www.indigo79.net/archives/27

like image 1
Michael Nash Avatar answered Nov 08 '22 18:11

Michael Nash