Pregunta

Example:

My application is doing a HTTP Connection. If I change to home screen using Home Button (fast app switching) the connection that my application was doing is canceled.

Why?

Are there some way to avoid it?

¿Fue útil?

Solución

Unfortunately (or depending on how you look at it, fortunately, since it saves battery life), when an app is deactivated due to a home button press, most HTTP connections will be canceled, and most operations suspended. This code from this blog post would check as to whether or not an HttpWebRequest was canceled by app deactivation (tombstoning):

    try
    {
         HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(MyResultAsync);
    }
    catch (WebException e)
    {
        if (e.Status == WebExceptionStatus.RequestCanceled)
            MessageBox.Show("Looks like your request was interrupted by tombstoning");
        else
        {
            using (HttpWebResponse response = (HttpWebResponse)e.Response)
            {
                MessageBox.Show("I got an http error of: " + response.StatusCode.ToString());
            }
        }
    }

If you want to download / upload a file in the background, you can take a look at this article. For any more complex types of network operations, you're out of luck.

Otros consejos

No, there is no way to avoid this. When you Fast-App-Switch all your web requests will be cancelled.

If it was cancelled you'll be able to detect this in the exception you get when returning to the app:

catch (WebException webEx)
{
    if (webEx.Status == WebExceptionStatus.RequestCanceled)
    {
        // Retry request
    }
    else
    {
        // Handle other exception 
    }
}

If your application has other ways of (manually) cancelling requests then you'll need to account for these as well.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top