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?
CancellationTokens as well as tasks are one-time entities and should be thrown away after use.
Basic approach in you case will be:
CancellationTokenSource;CancellationToken;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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With