Create helper class
public class AsyncTimer
{
private readonly Func<Task> _action;
private readonly int _period;
private readonly CancellationToken _cancellationToken;
public AsyncTimer(Func<Task> action, int period, CancellationToken cancellationToken)
{
_action = action ?? throw new ArgumentNullException(nameof(action));
_period = period;
_cancellationToken = cancellationToken;
}
public async Task StartAsync()
{
while (!_cancellationToken.IsCancellationRequested)
{
await _action();
try
{
await Task.Delay(_period, _cancellationToken);
}
catch (TaskCanceledException)
{
break;
}
}
}
}
How to use
Create function timer 1s
private async Task CheckStatusAsync()
{
CancellationTokenSource cts = new CancellationTokenSource(); // cts.Cancel() for calcel timer
AsyncTimer timer = new AsyncTimer(
async () =>
{
await Task.Run(() =>
{
//Something here
});
},
1000,
cts.Token);
await timer.StartAsync();
}
And now you can put this function where you want to use !
Post a Comment