gpt4 book ai didi

c# - 以高分辨率间隔/计时器引发事件

转载 作者:可可西里 更新时间:2023-11-01 03:13:41 24 4
gpt4 key购买 nike

我想通过 C# 使用最高分辨率的计时器。例如,我想每 11 个滴答声引发一个事件(我听说滴答声是 pc 中可能的最高计数器)。我尝试了计时器,发现最短耗时以毫秒为单位。我查看了秒表,但秒表没有引发事件。

谢谢。

最佳答案

使用多媒体计时器应该可以为您提供每秒大约 1000 个事件。此代码应该对您有所帮助。

     public delegate void TimerEventHandler(UInt32 id, UInt32 msg, ref UInt32 userCtx, UInt32 rsv1, UInt32 rsv2);

/// <summary>
/// A multi media timer with millisecond precision
/// </summary>
/// <param name="msDelay">One event every msDelay milliseconds</param>
/// <param name="msResolution">Timer precision indication (lower value is more precise but resource unfriendly)</param>
/// <param name="handler">delegate to start</param>
/// <param name="userCtx">callBack data </param>
/// <param name="eventType">one event or multiple events</param>
/// <remarks>Dont forget to call timeKillEvent!</remarks>
/// <returns>0 on failure or any other value as a timer id to use for timeKillEvent</returns>
[DllImport("winmm.dll", SetLastError = true,EntryPoint="timeSetEvent")]
static extern UInt32 timeSetEvent(UInt32 msDelay, UInt32 msResolution, TimerEventHandler handler, ref UInt32 userCtx, UInt32 eventType);

/// <summary>
/// The multi media timer stop function
/// </summary>
/// <param name="uTimerID">timer id from timeSetEvent</param>
/// <remarks>This function stops the timer</remarks>
[DllImport("winmm.dll", SetLastError = true)]
static extern void timeKillEvent( UInt32 uTimerID );

请务必在运行后停止这些计时器。它们对您的系统来说非常沉重*。一定要捕获所有异常,不要让它们逃脱您的事件处理程序。

*启动超过 5 个计时器会严重降低大多数系统的速度!在事件处理程序中执行尽可能少的代码,并确保执行代码快于 1 毫秒,否则将面临严重问题。我每 10-50 个刻度开始一个代表以增加标签显示。

发生在 Thread.Sleep 上的正常线程切换将使一个线程槽没有您的代码,并且大约需要 40 毫秒。您还可以通过一些 NT 内核调用来增加线程切换频率,但请不要那样做。

关于c# - 以高分辨率间隔/计时器引发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4212611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com