简体   繁体   中英

HttpClient GetAsync fails in background task on Windows 8

I have a Win RT app that has a background task responsible for calling an API to retrieve data it needs to update itself. However, I've run into a problem; the request to call the API works perfectly when run outside of the background task. Inside of the background task, it fails, and also hides any exception that could help point to the problem.

I tracked this problem through the debugger to track the problem point, and verified that the execution stops on GetAsync. (The URL I'm passing is valid, and the URL responds in less than a second)

var client = new HttpClient("http://www.some-base-url.com/");

try
{
    response = await client.GetAsync("valid-url");

    // Never gets here
    Debug.WriteLine("Done!");
}
catch (Exception exception)
{
    // No exception is thrown, never gets here
    Debug.WriteLine("Das Exception! " + exception);
}

All documentation I've read says that a background task is allowed to have as much network traffic as it needs (throttled of course). So, I don't understand why this would fail, or know of any other way to diagnose the problem. What am I missing?


UPDATE/ANSWER

Thanks to Steven, he pointed the way to the problem. In the interest of making sure the defined answer is out there, here was the background task before and after the fix:

Before

public void Run(IBackgroundTaskInstance taskInstance)
{
    BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

    Update();

    deferral.Complete();
}

public async void Update()
{
    ...
}

After

public async void Run(IBackgroundTaskInstance taskInstance) // added 'async'
{
    BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

    await Update(); // added 'await'

    deferral.Complete();
}

public async Task Update() // 'void' changed to 'Task'
{
    ...
}

您必须调用IBackgroundTaskInterface.GetDeferral ,然后在Task完成时调用其Complete方法。

Following is the way I am doing it and it works for me

        // Create a New HttpClient object.
        var handler = new HttpClientHandler {AllowAutoRedirect = false};
        var client = new HttpClient(handler);
        client.DefaultRequestHeaders.Add("user-agent",
                                         "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

        var response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();

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