Timer rework
This commit is contained in:
parent
4b33339d3a
commit
c31370f37a
@ -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);
|
||||
}
|
||||
|
||||
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 Start() => _timerTask.Start();
|
||||
|
||||
// завершение потока
|
||||
public void Stop()
|
||||
{
|
||||
Repeat = false;
|
||||
кансель.Cancel();
|
||||
_cts.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user