Skip to content

Instantly share code, notes, and snippets.

@maliming
Last active October 15, 2021 13:53
Show Gist options
  • Save maliming/359f708c5f9873e9a1c065cb02ab8bf4 to your computer and use it in GitHub Desktop.
Save maliming/359f708c5f9873e9a1c065cb02ab8bf4 to your computer and use it in GitHub Desktop.
var i = 1;
var timer = new AsyncTimer(1000, false)
{
Callback = async (timer, token) =>
{
Console.WriteLine(i++);
if (i > 5)
{
await timer.StopAsync();
}
}
};
await timer.StartAsync();
Console.WriteLine("Hello, World!");
public class AsyncTimer
{
public Func<AsyncTimer, CancellationToken, Task> Callback;
private readonly int _period;
private readonly bool _runOnStart;
private readonly CancellationTokenSource _cancellationTokenSource;
public AsyncTimer(int period, bool runOnStart = false)
{
_period = period;
_runOnStart = runOnStart;
_cancellationTokenSource = new CancellationTokenSource();
Callback = (_, _) => Task.CompletedTask;
}
public async Task StartAsync()
{
var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(_period));
if (_runOnStart)
{
await Callback(this, _cancellationTokenSource.Token);
}
try
{
while (await timer.WaitForNextTickAsync(_cancellationTokenSource.Token))
{
await Callback(this, _cancellationTokenSource.Token);
}
}
catch (TaskCanceledException e)
{
//The task canceled
}
catch (OperationCanceledException)
{
//The operation has been completed with an error before the cancellation takes effect
}
catch (Exception)
{
//The operation has been completed with an error before the cancellation takes effect
throw;
}
finally
{
_cancellationTokenSource.Dispose();
}
}
public Task StopAsync()
{
_cancellationTokenSource.Cancel();
return Task.CompletedTask;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment