Non-reentrant timers

后端 未结 5 484
别那么骄傲
别那么骄傲 2020-12-11 04:30

I have a function that I want to invoke every x seconds, but I want it to be thread-safe.

Can I set up this behavior when I am creating the timer? (I don\'t

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 04:59

    I'm guessing, as your question is not entirely clear, that you want to ensure that your timer cannot re-enter your callback whilst you are processing a callback, and you want to do this without locking. You can achieve this using a System.Timers.Timer and ensuring that the AutoReset property is set to false. This will ensure that you have to trigger the timer on each interval manually, thus preventing any reentrancy:

    public class NoLockTimer : IDisposable
    {
        private readonly Timer _timer;
    
        public NoLockTimer()
        {
            _timer = new Timer { AutoReset = false, Interval = 1000 };
    
            _timer.Elapsed += delegate
            {
                //Do some stuff
    
                _timer.Start(); // <- Manual restart.
            };
    
            _timer.Start();
        }
    
        public void Dispose()
        {
            if (_timer != null)
            {
                _timer.Dispose();
            }
        }
    } 
    

提交回复
热议问题