Search code examples
c#taskcancellationtokensource

cancelling tasks with cancellation tokens


I have a task which gets my data. I have another property that if changed cancels the Task and starts the Task again but with a different parameter shown below.

private CancellationTokenSource CTS = new CancellationTokenSource();

private void LoadMyStuff(string parameter)
{          
     Task<List<Stuff>> loadStuff = new Task<List<Stuff>>(() => ServiceMethod(parameter));
     loadStuff.Start();
     loadStuff.ContinueWith((Sender) =>
     {
           foreach (var entry in Sender.Result)
           {
               if (!CTS.IsCancellationRequested)
               {
                   //Proccess my data      
               }
               else
               {
                   CTS.Cancel();
                   return;
               }
            }
     }, CTS.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());
     loadStuff.ContinueWith((Sender) =>
     {
          //Clean Up
     }, CTS.Token, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
 }

Property:

private Thing _myThing
public Thing MyThing
{
   get { return _myThing; }
   set 
     {
        _myThing= value;
        CTS.Cancel();
        LoadMyStuff(parameter); 
     }
}

So my problem is I am always cancelling the task before it even completes in this instance. How do I get this scenario where the first instance of the task cancels but the second fired from the MyThing property runs through to completion?


Solution

  • You have to create a new CancellationTokenSource.

    Once a CancellationTokenSource is signaled, all its token will be signaled as well, and they'll remain that way. So if you want to start a new task, you need a brand new token source.