How to fire timer.Elapsed event immediately

前端 未结 10 1227
独厮守ぢ
独厮守ぢ 2020-12-10 00:17

I\'m using the System.Timers.Timer class to create a timer with an Timer.Elapsed event. The thing is the Timer.Elapsed event is fired

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 00:59

    I know this answer is late but if you want your System.Timers.Timer to be fired within 100ms (default interval) then you could simply just initialize the Timer object without a specified interval, then set the interval within the called function to whatever you like. Here is an example of what I use in my Windows Service:

    private static Timer _timer;
    
    protected override void OnStart(string[] args)
    {
        _timer = new Timer(); //This will set the default interval
        _timer.AutoReset = false;
        _timer.Elapsed = OnTimer;
        _timer.Start();
    }
    
    private void OnTimer(object sender, ElapsedEventArgs args)
    {
        //Do some work here
        _timer.Stop();
        _timer.Interval = 50000; //Set your new interval here
        _timer.Start();
    }
    

提交回复
热议问题