c# single-threaded-timer

Wollte ich einen timer mit den folgenden Eigenschaften:

  1. Egal wie viele Male starten aufgerufen wird, nur ein call-back-thread wird immer ausgeführt

  2. Die Zeit, in der call-back-Funktion wurde nicht mit Bezug auf das Intervall. E. g, wenn das Intervall 100ms und die rufen zurück nimmt 4000ms zu führen, der callback wird aufgerufen, bei 100ms, 4100ms etc.

Konnte ich nicht sehen, nichts zur Verfügung, so schrieb Sie den folgenden code. Gibt es einen besseren Weg, dies zu tun?

/**
 * Will ensure that only one thread is ever in the callback
 */
public class SingleThreadedTimer : Timer
{
    protected static readonly object InstanceLock = new object();

    //used to check whether timer has been disposed while in call back
    protected bool running = false;

    virtual new public void Start()
    {
        lock (InstanceLock)
        {
            this.AutoReset = false;
            this.Elapsed -= new ElapsedEventHandler(SingleThreadedTimer_Elapsed);
            this.Elapsed += new ElapsedEventHandler(SingleThreadedTimer_Elapsed);
            this.running = true;
            base.Start();
        }

    }

    virtual public void SingleThreadedTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        lock (InstanceLock)
        {
            DoSomethingCool();

            //check if stopped while we were waiting for the lock, we don't want to restart if this is the case..
            if (running)
            {
                this.Start();
            }
        }
    }

    virtual new public void Stop()
    {
        lock (InstanceLock)
        {
            running = false;
            base.Stop();
        }
    }
}
Schreibe einen Kommentar