A cancellable polling Task using CancellationTokenSource
suggest changepublic class Foo
{
    private CancellationTokenSource _cts;
    public Foo()
    {
        this._cts = new CancellationTokenSource();
    }
    public void StartExecution()
    {
        Task.Factory.StartNew(this.OwnCodeCancelableTask, this._cts.Token);
    }
    public void CancelExecution()
    {
        this._cts.Cancel();
    }
    /// <summary>
    /// "Infinite" loop with no delays. Writing to a database while pulling from a buffer for example.
    /// </summary>
    /// <param name="taskState">The cancellation token from our _cts field, passed in the StartNew call</param>
    private void OwnCodeCancelableTask(object taskState)
    {
        var token = (CancellationToken) taskState; //Our cancellation token passed from StartNew();
        while ( !token.IsCancellationRequested )
        {
            Console.WriteLine("Do your task work in this loop");
        }
    }
}
	
  Found a mistake? Have a question or improvement idea?
  Let me know.
      
      Table Of Contents