Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

c# - Raise event in high resolution interval/timer

I want to use the highest possible resolution timer using c#. For example, I want to raise an event every 11 ticks (I've heard that tick is the highest possible counter in pc). I tried timer and found that minimum elapsed time is in milliseconds. I looked at stopwatch but stopwatch doesn't raise events.

Thanks.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using a multimedia timer should give you about 1000 events per second. This code should help you on the way.

     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 );

Do stop these timers after running them. They are quite heavy on your system*. Do catch all exceptions and don't let them escape your event handler.

*Starting more then 5 timers will seriously slow down most systems! Execute as little as possible code in the event handlers and make sure the executing code is faster then 1 millisecond or face serious problems. I started a delegate every 10-50 ticks to increase a label display.

A normal thread switch that occurs on a Thread.Sleep will leave one thread-slot free of your code and will take about 40 milliseconds. You can also increase the thread switch frequency with some NT kernel calls, but please, don't do that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...