Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to create a new CancellationTokenSource(); after a task cancel?

Tags:

c#

I have an application like this:

I have an application where a portion of the code runs in a loop with a timer delay. At the start of the application I declare:

public static CancellationTokenSource tokenSource1 = new CancellationTokenSource();
public static bool Timer1Running;

Here’s the looping area:

 while (App.runCardTimer && App.TimerSeconds > 0)
 {
   App.Timer1Running = true;    
   …
   try
   {
      await Task.Delay(1000, App.tokenSource2.Token);
   }
   catch (TaskCanceledException ex) { }
   App.TimerSeconds--;       
   App.Timer1Running = false;    
 }   

My application responds to a click on the screen like this:

wordGrid.GestureRecognizers.Add(       
   new TapGestureRecognizer()      
   {          
      Command = new Command(() =>          
      {          
         App.TimerSeconds = 0;          
         if (App.tokenSource1 != null && App.Timer1Running)          
         {              
            App.tokenSource1.Cancel();          
         }       
      })    
   });

I am confused about the Cancellation Token. Once I issue the statement:

App.tokenSource1.Cancel(); 

Do I need to create a new Cancellation Token like this:

tokenSource1 = new CancellationTokenSource();

Or can I keep reusing?

like image 828
Alan2 Avatar asked Aug 28 '17 09:08

Alan2


2 Answers

CancellationTokens as well as tasks are one-time entities and should be thrown away after use.

Basic approach in you case will be:

  • create CancellationTokenSource;
  • fire task(s) and pass it(them) CancellationToken;
  • wait for task(s) completion, cancellation or failure;
  • if you need to repeat operation, go to first list item.
like image 141
Dennis Avatar answered Oct 05 '22 23:10

Dennis


If you want to reset the state of the cancellation token, then there is no way to do this. You have to recreate the CancellationTokenSource.

like image 26
Kapol Avatar answered Oct 05 '22 23:10

Kapol