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

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

问题描述

我正在尝试重建一个旧的节拍器应用程序,该应用程序最初是使用 C++ 中的 MFC 编写的,现在使用 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 窗体,但实际上您可能会发现 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.

另一种方法可能是调用/调用 Win32 多媒体计时器 - timeGetTime、timeSetPeriod 等.

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

一个快速的谷歌找到了这个,这可能很有用 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天全站免登陆