Can I make this TimerQueueTimer class more perfect?

using System;
using System.Threading;

internal class TimerQueueTimer : IDisposable
{
    public TimerQueueTimer(int interval, int msBeforeFirstCall)
    {
        this.interval = interval;
        this.msBeforeFirstCall = msBeforeFirstCall;
        this.callback = this.ticked;
        this.isTheFirstTick = true;
        this.isStopped = true;
    }

    public event EventHandler Ticked;

    public void Start()
    {
        if (!this.isStopped)
        {
            return;
        }

        this.isTheFirstTick = true;
        this.isStopped = false;
        Computer.ChangeTimerResolutionTo(1);
        NativeMethods.CreateTimerQueueTimer(
            out this.handle,
            IntPtr.Zero,
            this.callback,
            IntPtr.Zero,
            (uint)this.msBeforeFirstCall,
            (uint)this.interval,
            CallbackExecution.ExecuteInTimerThread);
    }

    public void Stop()
    {
        if (this.isStopped)
        {
            return;
        }

        NativeMethods.DeleteTimerQueueTimer(
            IntPtr.Zero,
            this.handle,
            IntPtr.Zero);
        Computer.ClearTimerResolutionChangeTo(1);
        this.isStopped = true;
    }

    public void Dispose()
    {
        this.Stop();
    }

    private void ticked(IntPtr parameterPointer, bool timerOrWaitFired)
    {
        if (this.isStopped)
        {
            return;
        }

        if (this.isTheFirstTick)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
        }

        this.isTheFirstTick = false;
        var ticked = this.Ticked;
        if (ticked != null)
        {
            ticked(this, EventArgs.Empty);
        }
    }

    private IntPtr handle;
    private volatile bool isStopped;
    private volatile bool isTheFirstTick;
    private readonly WaitOrTimerDelegate callback;
    private readonly int interval;
    private readonly int msBeforeFirstCall;
}

(Note: Computer.ChangeTimerResolutionTo()and Computer.ClearTimerResolutionChangeTo()call timeBeginPeriodand, timeEndPeriodrespectively.)

Questions:

  • The callback is executed in the timer thread, not in the ThreadPool thread. It's ok if the callback function is fast, right?
  • Does the priority of the return stream (and therefore the timer stream) give the highest result in terms of performance?
  • It would be better to make a timer interval of 1 ms and count ticks, raising Tickedif tickCount % interval == 0? A more accurate and accurate lower interval timer?
  • Is there a reason why this might be less accurate and / or accurate than a similarly created timer timeSetEvent?

, , , , 50 , . , timeSetEvent, , - . , Windows , . , , , , . - , ?

+3
1

: ( ), , .

"" - , - . , , , , .

, , .

, , , .

-1

All Articles