timer rewritten

This commit is contained in:
Timerix 2021-10-14 12:05:49 +03:00
parent 398866cb7b
commit a91220d390

View File

@ -1,5 +1,6 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace DTLib
{
@ -8,30 +9,34 @@ namespace DTLib
//
public class Timer
{
Thread TimerThread;
Task TimerTask;
bool Repeat;
CancellationTokenSource кансель = new();
// таймер сразу запускается
public Timer(bool repeat, int delay, Action method)
{
Repeat=repeat;
TimerThread=new Thread(() =>
TimerTask=new Task(() =>
{
do
{
Thread.Sleep(delay);
if(кансель.Token.IsCancellationRequested)
return;
Task.Delay(delay).Wait();
method();
} while(Repeat);
});
}
public void Start() => TimerThread.Start();
public void Start() => TimerTask.Start();
// завершение потока
public void Stop()
{
Repeat=false;
TimerThread.Abort();
кансель.Cancel();
}
}
}