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