简体   繁体   中英

Windows store app HttpClient issue

i'm testing some code here and came across a really weird issue. The HttpClient class works like a charm if my tablet is on but whenever the battery safe state kicks in and the screen is locked the HttpClient class throw an exception and the app suddendly exits giving me small chances to log the exception. If i'm not mistaken the error seems to be a send request error but that's weird since i have full access to the internet while the tablet is on.

Here the code i'm using and the one that crash on that state(System.Net.Http namespace ):

private static async Task<string> HttpGet(string uri)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("User-Agent", BotUserAgent);
            var response = await client.GetAsync(uri);
            return await response.Content.ReadAsStringAsync();
        }
    }

Alternatively i've used the client of the web.http namespace with the same result:

using(var client = new Windows.Web.Http.HttpClient())
        {
            client.DefaultRequestHeaders.Add("User-Agent", BotUserAgent);
            var response = await client.GetAsync(new Uri(uri));
            return await response.Content.ReadAsStringAsync();
        }

This is the error i get(after adding an exception logger):

An error occurred while sending the request.

Any ideas?

The problem is that your WinRT-device sends your app to the background when the battery safe state kiks in.

whenever the user moves your app into the background, your app can be suspended or frozen, essentially stopping any downloads dead in their tracks. In some scenarios, the app might even be terminated, forcing you to create a new instance of the class in an attempt to start the download again. Fortunately, WinRT provides a way to handle this specific scenario using a background task.

This is a quote from http://www.informit.com/articles/article.aspx?p=2229233&seqNum=6

On this site is an easy tutorial to follow on how to use BackgroundTransfers in the Windows.Networking.BackgroundTransfer-Namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM