从C#中的计时器获取准确的滴答 [英] Getting accurate ticks from a timer in C#

查看:128
本文介绍了从C#中的计时器获取准确的滴答的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重建一个原来的节拍器应用程序,该应用程序最初是使用MFC在C ++中编写的,然后将使用C#在.NET中编写。我遇到的问题之一是使计时器足够准确地滴答。

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.

例如,假设一个简单的BPM(每分钟心跳数)为120,计时器应每0.5秒(或500毫秒)计时一次。但是,使用此值作为滴答的基础并不完全准确,因为.NET仅保证您的计时器不会在经过的时间过去之前滴答。

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.

当前,要针对上面使用的相同的120 BPM示例解决此问题,我将刻度设置为大约100毫秒,并且仅在每5个计时器刻度上播放一次咔嗒声。确实确实可以提高一些准确性,但是如果感觉有点像骇客。

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.

那么,获得准确刻度的最佳方法是什么?我知道可以使用的计时器比Visual Studio中可以使用的Windows窗体计时器要多,但是我对它们并不真正熟悉。

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.

推荐答案

.NET中有三个称为 Timer的计时器类。听起来您正在使用Windows Forms,但实际上您可能会发现System.Threading.Timer类更有用-但要小心,因为它会调用池线程,因此您不能直接从

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 /调用Win32多媒体计时器-timeGetTime,timeSetPeriod等。

Another approach might be to p/invoke to the Win32 multimedia timers - timeGetTime, timeSetPeriod, etc.

一个快速的Google发现了这一点, http://www.codeproject可能很有用。 com / KB / miscctrl / lescsmultimediatimer.aspx

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.

这篇关于从C#中的计时器获取准确的滴答的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆