Use of Timer in Windows Service

后端 未结 6 1839
轻奢々
轻奢々 2020-12-12 23:08

I have a windows service where in I want to create a file every 10 seconds.

I got many reviews that Timer in Windows service would be the best option.

How ca

6条回答
  •  时光说笑
    2020-12-12 23:38

    I would not recommend System.Timers.Timer since it silently eats unhandled exceptions and therefore hides errors that you should fix. imho better that your code blows up in your face if you do not handle exceptions properly.

    As for System.Threading.Timer I tend to use the Change method to start/stop the timer in a pattern like this:

    public class MyCoolService
    {
        Timer _timer;
    
        public MyCoolService()
        {
            _timer = new Timer(MyWorkerMethod, Timeout.Infinite, Timeout.Infinite);
        }
    
        protected void OnStart()
        {
            _timer.Change(15000, Timeout.Infinte);
        }
    
        protected void MyWorkerMethod()
        {
            //pause timer during processing so it
            // wont be run twice if the processing takes longer
            // than the interval for some reason
            _timer.Change(Timeout.Infinite, Timeout.Infinite); 
    
            try
            {
                DoSomeWork();
            }
            catch (Exception err)
            {
                // report the error to your manager if you dare
            }
    
            // launch again in 15 seconds
            _timer.Change(15000, Timeout.Infinite);
        }
    
    }
    

提交回复
热议问题