diff --git a/DTLib/Timer.cs b/DTLib/Timer.cs index 9b5dc2b..3200d8a 100644 --- a/DTLib/Timer.cs +++ b/DTLib/Timer.cs @@ -7,33 +7,39 @@ namespace DTLib; // public class Timer { - Task TimerTask; - bool Repeat; - CancellationTokenSource кансель = new(); + private Task _timerTask; + private CancellationTokenSource _cts = new(); + private bool _repeat; + private int _delayMs; + private Action _action; // таймер сразу запускается - public Timer(bool repeat, int delay, Action method) + public Timer(bool repeat, int delayMs, Action action) { - Repeat = repeat; - TimerTask = new Task(() => - { - do - { - if (кансель.Token.IsCancellationRequested) - return; - Task.Delay(delay).Wait(); - method(); - } while (Repeat); - }); + _repeat = repeat; + _delayMs = delayMs; + _action = action; + _timerTask = new Task(Loop, _cts.Token); } - - public void Start() => TimerTask.Start(); + private void Loop() + { + do + { + if (_cts.Token.IsCancellationRequested) + return; + Task.Delay(_delayMs).Wait(); + if (_cts.Token.IsCancellationRequested) + return; + _action?.Invoke(); + } while (_repeat); + } + + public void Start() => _timerTask.Start(); // завершение потока public void Stop() { - Repeat = false; - кансель.Cancel(); + _cts.Cancel(); } }