做一个更准确的计时器.c#中的计时器存在于c++中

Does a more accurate Timers.Timer from c# exists in c++?

本文关键字:计时器 存在 c++ 一个      更新时间:2023-10-16

我在c#中有一个计时器,每10毫秒执行一个线程:

        private void setTimers(IntPtr paramA, List<int> paramB)
    {
        varTimer= new System.Timers.Timer();
        varTimer.Elapsed += delegate { Check(paramA, paramB); };
        varTimer.Interval = 10;
        varTimer.Start();
    }

功能:

private void Check(IntPtr paramA, List<int> paramB)
    {
            try
            {
                acquiredLock= false;
                System.Threading.Monitor.TryEnter(syncThreadsC, ref acquiredLock);
                if (acquiredLock)
                {
                    // logic
                }
                else
                {
                    return;
                }
            }
            finally
            {
                if (acquiredLock)
                    System.Threading.Monitor.Exit(syncThreadsC);
            }
    }

我要求它每10毫秒启动一次,即使知道它不会非常精确,当我进入和退出Check时,如果我检查StopWatch,我会得到这些数字:

[605] [668] [693] [755] [785] [847] [878] [941] [971] [40] [67] [128][159]

Check的逻辑只需要1到2 ms。我想知道,因为我相信c#中没有什么比这更精确的了,如果c++中有任何东西可以每X毫秒以更高的精度启动一个计时器。如果是这样,我将在一个外部dll中调用它。这些数字离我需要的太远了。

谢谢

在高分辨率interval/timer中使用Raise事件的正确计时器类,这里是一个高分辨率计时器的示例实现:

class Program
{
    public void Main(string[] args)
    {
        uint timerId = SafeNativeMethods.timeSetEvent( 1, 1, HandleTimerTick, UIntPtr.Zero, 1 );
        Console.ReadLine();
        SafeNativeMethods.timeKillEvent( timerId );
    }
    public static void HandleTimerTick( uint id, uint msg, UIntPtr userCtx, UIntPtr uIntPtr, UIntPtr intPtr )
    {
        Console.WriteLine( "This is a bad idea on short timescales" );
    }
}
public static class SafeNativeMethods
{
    /// <summary>
    /// A timer event handler
    /// </summary>
    /// <param name="id">Timer identifier, as returned by the timeSetEvent function.</param>
    /// <param name="msg">Reserved</param>
    /// <param name="userCtx">The value that was passed in to the userCtx value of the timeSetEvent function.</param>
    /// <param name="dw1">Reserved</param>
    /// <param name="dw2">Reserved</param>
    public delegate void TimerEventHandler( UInt32 id, UInt32 msg, UIntPtr userCtx, UIntPtr dw1, UIntPtr dw2 );
    /// <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" )]
    public static extern UInt32 timeSetEvent( UInt32 msDelay, UInt32 msResolution, TimerEventHandler handler, UIntPtr 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 )]
    public static extern void timeKillEvent( UInt32 uTimerID );
}

请确保在你用完计时器后干净利落地终止它,使用timeKillEvent,请不要在你的应用程序中使用大量这样的计时器。