Hi Friends, and Happy Christmas to all of you.
I have this problem.
I have an app that, on OnStart(), create a Task
Task.Run(async()=> startTimer (60000));
this startTimer() has this code...
private async Task startTimer(int delay){
await App.UpdateDateTime (); // DO SOME WORKS
App.CancellationToken = new CancellationTokenSource ();
TimerRunning (delay, App.CancellationToken.Token);
}
private async void TimerRunning(int delay, CancellationToken token)
{
Debug.WriteLine ("Timer attivato");
while (!token.IsCancellationRequested)
{
try
{
await Task.Delay(delay , token); // WAIT...
}
catch (TaskCanceledException)
{
}
try{
if (!token.IsCancellationRequested) {
await App.UpdateDateTime (); // REDO SOME WORKS
}
}
catch{
}
}
}
Then, on OnSleep() I try to suspend the Timer
protected override void OnSleep ()
{
if (App.CancellationToken != null) {
App.CancellationToken.Cancel ();
App.CancellationToken = null;
}
}
It seems to work.
I have only this problem.
If I destroy my app (in Android visualizing all running app and switching my app to right...) I see that my app pass by "OnSleep" (so the thread should be cancelled), but if I RESTART my device (ON/OFF button and select Reset), at the startup i see this message
Unfortunately, (my app name) has stopped.
I have tried to comment the line (in OnStart())
Task.Run(async()=> startTimer (60000));
and do all steps (run my app, destroy it, restart the device...) and the "Unfortunately" message does not appear, so I think it's a "Task" problem.
Can someone explain to me how can I solve this situation? There is some way to destroy all Tasks before the app is killed?
Thanks