Windows Service System.Timers.Timer not firing

前端 未结 6 1919
走了就别回头了
走了就别回头了 2020-12-05 04:36

I have a Windows service written in C# which is meant to perform a task every few minutes. I\'m using a System.Timers.Timer for this but it doesn\'t ever appea

6条回答
  •  半阙折子戏
    2020-12-05 04:57

    I also had to switch to System.Threading.Timer. To make re-factoring easier and others live easy, I created a separate class, containing an instance of System.Threading.Timer and has almost the same methods as System.Timers.Timer, so that calling code requires minimal changes:

    /// 
    /// Custom Timer class, that is actually a wrapper over System.Threading.Timer
    /// 
    /// 
    internal class Timer : IDisposable
    {
        System.Threading.Timer _timer;
    
        public Timer()
        {
    
        }
        public Timer(int interval) : this()
        {
            this.Interval = interval;
        }
    
        public bool AutoReset { get; set; }
        public bool Enabled { get; set; }
        public int Interval { get; set; }
        public Action OnTimer { get; internal set; }
    
        public void Dispose()
        {
            if (_timer != null)
            {
                _timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                _timer.Dispose();
                _timer = null;
            }
        }
    
        public void Start()
        {
            _timer = new System.Threading.Timer(
                new System.Threading.TimerCallback(OnTimer), null, 0, Interval);
        }
        public void Stop()
        {
            if (_timer != null)
            {
                _timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
            }
        }
    }
    
    
    

    I hope this will help!

    提交回复
    热议问题