Events in Windows Phone 8 for apps and async / await
What happens to the expected task when the app goes into the background and then resumes? Assuming the Task was not canceled when the app suspended event was received. Is there a difference between resuming from the tombstone state and only from the background?
If there is no direct answer, i.e. it depends on the implementation of the service providing the asynchronous API, what are the best practices to follow in this case?
source to share
When an application goes into the background, all application threads are frozen. Thus, the task will resume after activating the application.
For example, run this piece of code:
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Debug.WriteLine("I've started");
await Task.Delay(TimeSpan.FromSeconds(5));
Debug.WriteLine("I'm done");
}
private void Application_Launching(object sender, LaunchingEventArgs e)
{
Debug.WriteLine("Application_Launching");
}
private void Application_Activated(object sender, ActivatedEventArgs e)
{
Debug.WriteLine("Application_Activated");
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
Debug.WriteLine("Application_Deactivated");
}
When we run this piece of code and hit the Start button before exiting for five seconds, we will see the following output:
Application_Launching
I began
Application_Deactivated
Application_Activated
I've finished
Based on the specified sequence of events, you can see that the asynchronous wait task completed after deactivation and activation.
In terms of best practices for asynchronous awaiting:
-
For any operation using an external resource (such as a WebRequest), it is best to have a try-catch block around it with some meaningful error handling. More details @ http://msdn.microsoft.com/en-us/library/dd997415.aspx
-
For long running tasks that make sense to terminate after deactivating the application, use the TaskCancellationToken mechanism to cancel those tasks. More details @ http://msdn.microsoft.com/en-us/library/dd997396.aspx
source to share