HttpClient GetAsync fails in background task on Windows 8

假装没事ソ 提交于 2019-12-03 19:55:59

问题


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'
{
    ...
}

回答1:


You have to call IBackgroundTaskInterface.GetDeferral and then call its Complete method when your Task is complete.




回答2:


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();


来源:https://stackoverflow.com/questions/13078635/httpclient-getasync-fails-in-background-task-on-windows-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!