DTLib/TImer.cs
2021-10-14 12:05:49 +03:00

43 lines
1.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Threading;
using System.Threading.Tasks;
namespace DTLib
{
//
// простой и понятный класс для выполнения каких-либо действий в отдельном потоке раз в некоторое время
//
public class Timer
{
Task TimerTask;
bool Repeat;
CancellationTokenSource кансель = new();
// таймер сразу запускается
public Timer(bool repeat, int delay, Action method)
{
Repeat=repeat;
TimerTask=new Task(() =>
{
do
{
if(кансель.Token.IsCancellationRequested)
return;
Task.Delay(delay).Wait();
method();
} while(Repeat);
});
}
public void Start() => TimerTask.Start();
// завершение потока
public void Stop()
{
Repeat=false;
кансель.Cancel();
}
}
}