<p>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.</p>

<p>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.</p>

<p>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.</p>

<p>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.</p>

[{'answer_id': 8764, 'author': 'Will Dean', 'author_id': 987, 'author_profile': 'https://Stackoverflow.com/users/987', 'pm_score': 5, 'selected': True, 'text': '<p>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.</p>\n\n<p>Another approach might be to p/invoke to the Win32 multimedia timers - timeGetTime, timeSetPeriod, etc.</p>\n\n<p>A quick google found this, which might be useful <a href="http://www.codeproject.com/KB/miscctrl/lescsmultimediatimer.aspx" rel="noreferrer">http://www.codeproject.com/KB/miscctrl/lescsmultimediatimer.aspx</a></p>\n\n<p>\'Multimedia\' (timer) is the buzz-word to search for in this context.</p>\n'}, {'answer_id': 8809, 'author': 'Coincoin', 'author_id': 42, 'author_profile': 'https://Stackoverflow.com/users/42', 'pm_score': 1, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 8865, 'author': 'Brad Barker', 'author_id': 12081, 'author_profile': 'https://Stackoverflow.com/users/12081', 'pm_score': 0, 'selected': False, 'text': "<p>Timer classes can start behaving strangely when the timer 'tick' event code is not finished executing by the time the next 'tick' occurs. One way to combat this is to disable the timer at the beginning of the tick event, then re-enable it at the end.</p>\n\n<p>However, this approach is not suitable in cases where the execution time of the 'tick' code is not acceptable error in the timing of the tick, since the timer will be disabled (not counting) during that time.</p>\n\n<p>If disabling the timer is an option, then you can also achieve the same effect by creating a separate thread that executes, sleeps for x milliseconds, executes, sleeps, etc...</p>\n"}, {'answer_id': 3852682, 'author': 'yazanpro', 'author_id': 465495, 'author_profile': 'https://Stackoverflow.com/users/465495', 'pm_score': 0, 'selected': False, 'text': '<p><code>System.Windows.Forms.Timer</code> is limited to an accuracy of 55 milliseconds...</p>\n'}, {'answer_id': 4967773, 'author': 'Michael Nash', 'author_id': 612860, 'author_profile': 'https://Stackoverflow.com/users/612860', 'pm_score': 1, 'selected': False, 'text': '<p>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:\n<a href="http://www.indigo79.net/archives/27" rel="nofollow">http://www.indigo79.net/archives/27</a></p>\n'}, {'answer_id': 27548804, 'author': 'yarony', 'author_id': 59403, 'author_profile': 'https://Stackoverflow.com/users/59403', 'pm_score': 1, 'selected': False, 'text': '<p>Another possibility is that there is a bug in WPF implementation of DispatcherTimer \n(there is a mismatch between milliseconds and ticks causing potential inaccuracy depending on exact process execution time) , as evidenced below:</p>\n\n<p><a href="http://referencesource.microsoft.com/#WindowsBase/Base/System/Windows/Threading/DispatcherTimer.cs,143" rel="nofollow">http://referencesource.microsoft.com/#WindowsBase/Base/System/Windows/Threading/DispatcherTimer.cs,143</a></p>\n\n<pre><code>class DispatcherTimer\n{\n    public TimeSpan Interval\n    {\n        set\n        {\n            ...\n            _interval = value;\n            // Notice below bug: ticks1 + milliseconds [Bug1]\n            _dueTimeInTicks = Environment.TickCount + (int)_interval.TotalMilliseconds;\n        }\n    }\n}\n</code></pre>\n\n<p><a href="http://referencesource.microsoft.com/#WindowsBase/Base/System/Windows/Threading/Dispatcher.cs" rel="nofollow">http://referencesource.microsoft.com/#WindowsBase/Base/System/Windows/Threading/Dispatcher.cs</a></p>\n\n<pre><code>class Dispatcher\n{\n    private object UpdateWin32TimerFromDispatcherThread(object unused)\n    {\n        ...\n        _dueTimeInTicks = timer._dueTimeInTicks;\n        SetWin32Timer(_dueTimeInTicks);\n    }\n\n    private void SetWin32Timer(int dueTimeInTicks)\n    {\n        ...\n        // Notice below bug: (ticks1 + milliseconds) - ticks2  [Bug2 - almost cancels Bug1, delta is mostly milliseconds not ticks]\n        int delta = dueTimeInTicks - Environment.TickCount; \n        SafeNativeMethods.SetTimer( \n            new HandleRef(this, _window.Value.Handle),\n            TIMERID_TIMERS,\n            delta); // &lt;-- [Bug3 - if delta is ticks, it should be divided by TimeSpan.TicksPerMillisecond = 10000]\n    }\n}\n</code></pre>\n\n<p><a href="http://referencesource.microsoft.com/#WindowsBase/Shared/MS/Win32/SafeNativeMethodsCLR.cs,505" rel="nofollow">http://referencesource.microsoft.com/#WindowsBase/Shared/MS/Win32/SafeNativeMethodsCLR.cs,505</a></p>\n\n<pre><code>class SafeNativeMethodsPrivate\n{\n    ...\n    [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]\n    public static extern IntPtr SetTimer(HandleRef hWnd, int nIDEvent, int uElapse, NativeMethods.TimerProc lpTimerFunc);\n}\n</code></pre>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms644906%28v=vs.85%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windows/desktop/ms644906%28v=vs.85%29.aspx</a></p>\n\n<pre><code>uElapse [in]\nType: UINT\nThe time-out value, in milliseconds. // &lt;-- milliseconds were needed eventually\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/8742', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1108/']