Only raise an event if the previous one was completed

后端 未结 4 867
误落风尘
误落风尘 2021-01-16 11:25

I\'m using a System.Timers.Timer in my application. Every second I run a function which does some job. The thing is, this function can block for some little tim

4条回答
  •  清歌不尽
    2021-01-16 12:09

    I'm not sure why you are using a new thread to start the timer, since timers run on their own thread, but here's a method that works. Simply turn the timer off until you are done with the current interval.

    static System.Timers.Timer oTimer
    
    public static void Main()
    {
        oTimer = new System.Timers.Timer();
        oTimer.Elapsed += new ElapsedEventHandler(Handler);
    
        oTimer.Interval = 1000;
        oTimer.Enabled = true;                 
    }
    
    private void Handler(object oSource, ElapsedEventArgs oElapsedEventArgs)
    {
        oTimer.Enabled = false;
    
        Console.WriteLine("foo");
        Thread.Sleep(5000);         //simulate some work
        Console.WriteLine("bar");
    
        oTimer.Enabled = true;
    }
    

提交回复
热议问题