为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
达令说 2019-12-04 15:00:43
我想通过c#使用尽可能高的分辨率计时器。例如,我想每11个滴答声触发一个事件(我听说滴答声是pc中可能的最高计数器)。我尝试使用计时器,发现最小经过的时间以毫秒为单位。我看着秒表,但秒表没有引发事件。谢谢。
查看完整描述

3 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

使用多媒体计时器应该可以为您每秒带来约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个滴答声启动一个代表,以增加标签显示。


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


查看完整回答
反对 回复 2019-12-04
  • 3 回答
  • 0 关注
  • 561 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信