Search code examples
c#async-awaitwindows-phonestreamreader

Windows Phone. Result of ReadToEndAsync() corrupted by app deactivation


I've got some troubles with StreamReader.ReadToEndAsync();

//some get response code ...
using (var response = getResponseTask.Result)
{
  using (var responseStream = response.GetResponseStream())
  {
    using (var responseStreamReader = new StreamReader(responseStream))
    {
     var readToEndTask = responseStreamReader.ReadToEndAsync();
     var responseResult = await readToEndTask;
     //and some json parse code here
    }
  }
}

So, when I press the Home button on the device (whatever phone or emulator) while ReadToEndAsync task is in process, result string is not full length on app reactivation... i.e. it's ending just cut out without any exceptions or warning.

As result, I can't parse my json-data to object.

How can I fix it or avoid this situation ?

Thanks everybody in advance!


Solution

  • For this, you need to run your code as a background task. Background tasks will run even your app is deactivated. You can refer : https://learn.microsoft.com/en-us/windows/uwp/launch-resume/support-your-app-with-background-tasks to learn background tasks. There are two types of background tasks, in process & out process.