I'm writing a simplified asynchronous event driven Timer
class. Just wondering if this will work under all conditions and if it's thread safe. IE, any chance of it failing during invoke or reading the Enabled property or setting the AutoReset
feature.
namespace Sandbox
{
public class AsyncTimer
{
public volatile bool AutoReset = true;
volatile bool enabled = false;
public volatile int Interval;
CancellationTokenSource? cts;
public volatile Action? Elapsed;
public bool Enabled { get { return enabled; } }
public AsyncTimer (int interval) => Interval = interval;
public void Start(bool startElapsed = false)
{
if (startElapsed) Elapsed?.Invoke();
enabled = true;
cts = new();
_ = Task.Run(() => RunTimerAsync());
}
public void Stop()
{
enabled = false;
cts?.Cancel();
}
async void RunTimerAsync()
{
while (enabled && !cts!.IsCancellationRequested)
{
await Task.Delay(Interval);
Elapsed?.Invoke();
if (!AutoReset) cts.Cancel();
}
}
}
}