How can i use a BackgroundWorker with a timer tick?

后端 未结 6 729
一向
一向 2020-12-06 04:10

Decided to not use any timers. What i did is simpler.

Added a backgroundworker. Added a Shown event the Shown event fire after all the constructor have been loaded.

6条回答
  •  伪装坚强ぢ
    2020-12-06 04:31

    I think BackgroundWorker is too complex thing for the case; with Timer it is difficult to implement guaranteed stopping.

    I would like to recommend you using worker Thread with the loop which waits cancellation ManualResetEvent for the interval you need:

    • If the cancellation event is set then the worker exits the loop.
    • If there is a timeout (time interval you need exceeds) then perform system monitoring.

    Here is the draft version of the code. Please note I have not tested it, but it could show you the idea.

    public class HardwareMonitor
    {
        private readonly object _locker = new object();
        private readonly TimeSpan _monitoringInterval;
        private readonly Thread _thread;
        private readonly ManualResetEvent _stoppingEvent = new ManualResetEvent(false);
        private readonly ManualResetEvent _stoppedEvent = new ManualResetEvent(false);
    
        public HardwareMonitor(TimeSpan monitoringInterval)
        {
            _monitoringInterval = monitoringInterval;
            _thread = new Thread(ThreadFunc)
                {
                    IsBackground = true
                };
        }
    
        public void Start()
        {
            lock (_locker)
            {
                if (!_stoppedEvent.WaitOne(0))
                    throw new InvalidOperationException("Already running");
    
                _stoppingEvent.Reset();
                _stoppedEvent.Reset();
                _thread.Start();
            }
        }
    
        public void Stop()
        {
            lock (_locker)
            {
                _stoppingEvent.Set();
            }
            _stoppedEvent.WaitOne();
        }
    
        private void ThreadFunc()
        {
            try
            {
                while (true)
                {
                    // Wait for time interval or cancellation event.
                    if (_stoppingEvent.WaitOne(_monitoringInterval))
                        break;
    
                    // Monitoring...
                    // NOTE: update UI elements using Invoke()/BeginInvoke() if required.
                }
            }
            finally
            {
                _stoppedEvent.Set();
            }
        }
    }
    

提交回复
热议问题