Reputation: 290
My application retrieves data from server by asynchronous calls to apis. It works fine as long as the user remains in app. After implementing Fast App Resume, when app resumes after clicking on the tile, the control comes to the page on which user left previously.
If there was any asynchronous call running when user had deactivated the app(hit the start button previously), it throws the following exception..
In fact this exception is thrown by the following code.
private async Task<string> httpRequest(HttpWebRequest request)
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory
.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
//cookieJar = request.CookieContainer;
//responseCookies = response.Cookies;
received = await sr.ReadToEndAsync();
}
}
}
return received.Replace("[{}]", "[]")
.Replace("[{},{}]", "[]")
.Replace("\"subcat_id\":\"\"", "\"subcat_id\":\"0\"");
}
Is there any way to stop execution of the async method on OnNavigatedFrom method when user deactivates the app? Or is there any way to preserve the state of async call and resume it again?
Thanks in advance.
Upvotes: 0
Views: 226
Reputation: 29790
When your App is Deactivated then all its proccesses are stopped (MSDN):
When the user navigates forward, away from an app, after the Deactivated event is raised, the operating system will attempt to put the app into a dormant state. In this state, all of the application’s threads are stopped and no processing takes place, but the application remains intact in memory.
Your async method should allow Cancellation - here you have an example of Cancelling.
Use CancellationTokenSource and then in your Deactivation event or OnNavigatedFrom put:
if (cts != null) cts.Cancel();
In your case you should also implement AsyncReading (via buffer) from response
to enable token.ThrowIfCancealltionRequested()
. You can look here - method 3 and here. Maybe it will help.
Upvotes: 1