Essential C# Task Parallel Library  Suggest an edit

An async cancellable polling Task that waits between iterations

public class Foo
    private const int TASK_ITERATION_DELAY_MS = 1000;
    private CancellationTokenSource _cts;

    public Foo()
        this._cts = new CancellationTokenSource();

    public void StartExecution()
        Task.Factory.StartNew(this.OwnCodeCancelableTask_EveryNSeconds, this._cts.Token);

    public void CancelExecution()

    /// <summary>
    /// "Infinite" loop that runs every N seconds. Good for checking for a heartbeat or updates.
    /// </summary>
    /// <param name="taskState">The cancellation token from our _cts field, passed in the StartNew call</param>
    private async void OwnCodeCancelableTask_EveryNSeconds(object taskState)
        var token = (CancellationToken)taskState;

        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);

Table Of Contents
22 Enum
107 Stream
108 Timers
115 Task Parallel Library
  ↑ ↓ to navigate     ↵ to select     Esc to close