Subway Application Controlled Timer (.NET)

I need a timer class that should provide functionality to start / stop / enable / disable and should be NON UI.

I see 2 options

I was thinking of creating a threadpool timer wrapper, but it seems very complicated since there is no / limited control over it.

How to create a timer class for the specified script. (I need something similar to System.Threading.Timer).

+4
source share
2 answers

Since the user interface must be very responsive in Metro applications - this may be enough to run DispatcherTimer and call Task.Run () for the things you want to run in the background thread.

If this does not work for you - see if this happens. It should have a similar API for DispatcherTimer, but work with a different thread. Not that he continued to wait for exactly the interval time, so the timer will be late. It is also not exactly thread safe, and I only played with it for 10 minutes, so it may not always work, but since it is open source, you can change it to fit your account.

public class BackgroundTimer { private AutoResetEvent _stopRequestEvent; private AutoResetEvent _stoppedEvent; #region Interval private TimeSpan _interval; public TimeSpan Interval { get { return _interval; } set { if (IsEnabled) { Stop(); _interval = value; Start(); } else { _interval = value; } } } #endregion public event EventHandler<object> Tick; #region IsEnabled private bool _isEnabled; public bool IsEnabled { get { return _isEnabled; } set { if (_isEnabled == value) return; if (value) Start(); else Stop(); } } #endregion public BackgroundTimer() { _stopRequestEvent = new AutoResetEvent(false); _stoppedEvent = new AutoResetEvent(false); } public void Start() { if (_isEnabled) { return; } _isEnabled = true; _stopRequestEvent.Reset(); Task.Run((Action)Run); } public void Stop() { if (!_isEnabled) { return; } _isEnabled = false; _stopRequestEvent.Set(); _stoppedEvent.WaitOne(); } private void Run() { while (_isEnabled) { _stopRequestEvent.WaitOne(_interval); if (_isEnabled && Tick != null) { Tick(this, null); } } _stoppedEvent.Set(); } } 
+4
source

I managed to create a watch with the following code:

 ThreadPoolTimer Timer1 = ThreadPoolTimer.CreatePeriodicTimer(Timer1_ElapsedHandler, TimeSpan.FromSeconds(1)); clockTick = false; UpdateLoop(); 

For this you need an event handler, in my watch it is established that the timer is marked:

 public void Timer1_ElapsedHandler(ThreadPoolTimer timer) { clockTick = true; } 

Then, to update the GUI (or whatever you need), there is an update loop:

 public async void UpdateLoop() { do { await Task.Delay(100); } while (!clockTick); ClockTextBlock.Text = DateTime.Now.ToString(); clockTick = false; UpdateLoop(); } 

Wrapping this in the class and clearing it up a bit can probably give you the basis for a good timer without a user interface.

0
source

Source: https://habr.com/ru/post/1411232/


All Articles