Timer rework

This commit is contained in:
Timerix22 2024-09-20 00:27:57 +05:00
parent 4b33339d3a
commit c31370f37a

View File

@ -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();
}
}