Alan2 Alan2 - 2 months ago 26
C# Question

How can I stop a running timer that runs in a while loop?

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;

await Task.Delay(1000, App.tokenSource1.Token);
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();
}
})
});


When it runs and when the screen is clicked it gets to the code
App.tokenSource1.Cancel()


However it then seems to stop.

Does anyone have any ideas what I might be doing wrong. I had expected the code to immediately go to the line
App.TimerSeconds--;
and didn’t expect it to just come to a stop before then.

Answer Source

await Task.Delay(1000, App.tokenSource1.Token);
throws System.Threading.Tasks.TaskCanceledException when canceled.
So you need to wrap it in try-catch:

{
   App.Timer1Running = true;    
   …
   try
   {
      await Task.Delay(1000, App.tokenSource1.Token);
   }
   catch(TaskCanceledException ex){}
   App.TimerSeconds--;       
   App.Timer1Running = false;    
}