Timer rework
This commit is contained in:
parent
4b33339d3a
commit
c31370f37a
@ -7,33 +7,39 @@ namespace DTLib;
|
|||||||
//
|
//
|
||||||
public class Timer
|
public class Timer
|
||||||
{
|
{
|
||||||
Task TimerTask;
|
private Task _timerTask;
|
||||||
bool Repeat;
|
private CancellationTokenSource _cts = new();
|
||||||
CancellationTokenSource кансель = 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;
|
_repeat = repeat;
|
||||||
TimerTask = new Task(() =>
|
_delayMs = delayMs;
|
||||||
{
|
_action = action;
|
||||||
do
|
_timerTask = new Task(Loop, _cts.Token);
|
||||||
{
|
|
||||||
if (кансель.Token.IsCancellationRequested)
|
|
||||||
return;
|
|
||||||
Task.Delay(delay).Wait();
|
|
||||||
method();
|
|
||||||
} while (Repeat);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void Loop()
|
||||||
public void Start() => TimerTask.Start();
|
{
|
||||||
|
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()
|
public void Stop()
|
||||||
{
|
{
|
||||||
Repeat = false;
|
_cts.Cancel();
|
||||||
кансель.Cancel();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user