An async cancellable polling Task that waits between iterations
suggest changepublic class Foo
{
private const int TASK_ITERATION_DELAY_MS = 1000;
private CancellationTokenSource _cts;
public Foo()
{
this._cts = new CancellationTokenSource();
}
public void StartExecution()
{
Task.Run(() => this.OwnCodeCancelableTask_EveryNSeconds(this._cts.Token));
}
public void CancelExecution()
{
this._cts.Cancel();
}
/// <summary>
/// "Infinite" loop that runs every N seconds. Good for checking for a heartbeat or updates.
/// </summary>
/// <param name="token">The cancellation token from our _cts field</param>
private async Task OwnCodeCancelableTask_EveryNSeconds(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
Console.WriteLine("Do the work that needs to happen every N seconds in this loop");
// Passing token here allows the Delay to be cancelled if your task gets cancelled.
await Task.Delay(TASK_ITERATION_DELAY_MS, token);
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents