我想要一个大约5毫秒分辨率的计时器.但.Net中的当前Timer具有大约50ms的分辨率.我找不到任何可以创建高分辨率计时器的工作解决方案,尽管有些人声称你可以用C#来做.
这是一个学术问题,因为我正在努力克服微软使用double作为Interval属性的数据类型的想法!
首先来自MDSN Interval是Elapsed事件之间的时间(以毫秒为单位); 我会将其解释为离散数,那么为什么要使用双?肯定是int或long更有意义!?
Inter Interval是否支持5.768585(5.768585 ms)等值?特别是当人们认为System.Timers.Timer无法达到亚毫秒精度时...... .NET中最准确的计时器?
对我来说似乎有些愚蠢..也许我错过了什么!
我正在使用C#/ Xaml开发Windows 10 Universal App,我正在使用等待Task.Delay(delayInMilliseconds)来暂停给定时间的方法.我的场景有点实时,因此它对时间变化非常敏感,我需要确保当我暂停一个方法让我们说8毫秒时,它会暂停8毫秒.我注意到**Task.Delay**暂停方法的实际时间跨度与传递的延迟参数不同,1到30毫秒,每次调用的"偏差"长度不同.所以,当我想睡8毫秒时,我的系统会睡眠9到39毫秒,这完全破坏了我的情景.所以,我的问题是什么是替换**Task.Delay**并获得良好精度的最佳方法?目前我使用这种方法:
public static void Delay1(int delay)
{
long mt = delay * TimeSpan.TicksPerMillisecond;
Stopwatch s = Stopwatch.StarNew();
while (true)
{
if (s.Elapsed.TotalMilliseconds > delay)
{
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它猜测它消耗了大量资源,即处理器核心的100%.如果用户具有少量处理器核心,则这将是非常不足的.
我正在开发一种音乐制作应用程序,其中包括音频播放。我目前遇到播放不一致的问题。我用来进行节拍的计时器似乎在某些滴答事件上跳过或滞后。您可以听到示例视频中的停顿: 视频
我像这样实现计时器及其事件
private void Method()
{
///some other code here
//the math for the timer period is to figure out how many times the timer should tick in 1 minute.
int _period = (int)Math.Round(60000f / (float)NUD_ConfigBPM.Value, MidpointRounding.AwayFromZero)
_threadtimer = new System.Threading.Timer(_ => _threadtimer_Tick(), null, 0, _period);
}
private void _threadtimer_Tick()
{
//vorbis is a List<List<CachedSound>>
//each beat can have several sounds to play at once
foreach (var _sample in vorbis[_playbackbeat]) {
AudioPlaybackEngine.Instance.PlaySound(_sample);
}
//simulating a playhead by highlighting …Run Code Online (Sandbox Code Playgroud) 我有一个功能,应该在一个特定的间隔后发送一个信号,精确到1毫秒(ms).但似乎我的计时器需要的时间比他应该的长,即我将功能传递给TimeSpan 20ms,但计时器需要每个刻度30ms.我现在自己写了一个计时器,Stopwatch但我还在想为什么计时器需要更多的时间来执行?
private System.Timers.Timer timer;
private void startResetTimer(TimeSpan time)
{
timer = new System.Timers.Timer(time.TotalMilliseconds);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
if (!waitForTimerReset.Set())
Console.WriteLine("Could not wake up any threads!");
}
Run Code Online (Sandbox Code Playgroud)
在我的代码中,计时器唯一执行的是waitForTimerReset.Set()允许线程在被a停止后继续运行的方法ManualResetEvent,这意味着此调用不应该花费10毫秒.