Question

What happens to await-ed Task when application goes to background, and then resumes? Presuming that Task was not cancelled when an event about the application suspending was received. Is there any difference between resuming from tombstone state and just from background?

If there's no direct answer, i.e. this depends on implementation of the service providing async API, what's the best practices to follow in this case?

Était-ce utile?

La solution

When the app goes into the background all of the app's threads are frozen. So the task will resume once the app has been activated.

For example, let's run this code snippet:

    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 code snippet, and hit the "Start" button before our five second are up we can see the following output:

Application_Launching

I've started

Application_Deactivated

Application_Activated

I'm done

Based on the above event sequence you can see an async-await task does complete after deactivation and activation.

In terms of best practices for async-await:

  1. For any operation using an external resource (e.g. WebRequest) it's best to have a try-catch block around it with some meaningful error handling. More @ http://msdn.microsoft.com/en-us/library/dd997415.aspx

  2. For long-running tasks that make sense to stop once the app gets deactivated use the TaskCancellationToken mechanism to cancel those tasks. More @ http://msdn.microsoft.com/en-us/library/dd997396.aspx

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top