I have a weather app which updates the weather periodically in a background task. When I run Windows App Certification Kit on my app, it fails background task cancellation test.
I read the official Microsoft documentation. I have implemented BackgroundTaskCanceledHandler. Here's the code.
volatile bool _CancelRequested = false;
protected async override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
{
args.TaskInstance.Canceled += new BackgroundTaskCanceledEventHandler(TaskInstance_Canceled);
// update weather tile
}
private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
_CancelRequested = true;
}
How do I stop execution of the code inside the OnBackgroundActivated method when TaskInstance_Canceled is called? If it was a loop, I would use while, but it's just a big chunk of code that executes only once.
Do I need to check if(_CancelRequested == true) on every line of code? That seems like a very unelegant solution, so there definitely has to be a better way.. Or, perhaps, I am clearly doing something wrong here.
I check the CancelRequested state after each awaited statement.