Execute specified function every X seconds

后端 未结 4 1853
小鲜肉
小鲜肉 2020-11-27 15:02

I have a Windows Forms application written in C#. The following function checks whenever printer is online or not:

public void isonline()
{
    PrinterSettin         


        
4条回答
  •  日久生厌
    2020-11-27 15:30

    Threaded:

        /// 
        /// Usage: var timer = SetIntervalThread(DoThis, 1000);
        /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
        /// 
        /// Returns a timer object which can be disposed.
        public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
        {
            TimerStateManager state = new TimerStateManager();
            System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
            state.TimerObject = tmr;
            return tmr;
        }
    

    Regular

        /// 
        /// Usage: var timer = SetInterval(DoThis, 1000);
        /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
        /// 
        /// Returns a timer object which can be stopped and disposed.
        public static System.Timers.Timer SetInterval(Action Act, int Interval)
        {
            System.Timers.Timer tmr = new System.Timers.Timer();
            tmr.Elapsed += (sender, args) => Act();
            tmr.AutoReset = true;
            tmr.Interval = Interval;
            tmr.Start();
    
            return tmr;
        }
    

提交回复
热议问题