An async cancellable polling Task that waits between iterations

suggest change
public 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);
        }
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents