HttpClient GetAsync在Windows 8上的后台任务失败 [英] HttpClient GetAsync fails in background task on Windows 8

查看:80
本文介绍了HttpClient GetAsync在Windows 8上的后台任务失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Win RT应用程序,它有一个后台任务,负责调用API来检索需要更新的数据.但是,我遇到了一个问题.在后台任务之外运行时,调用API的请求可以完美运行.在后台任务内部,它会失败,并且还会隐藏任何可能有助于指出问题的异常.

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.

我通过调试器跟踪了此问题以跟踪问题点,并验证了该执行在GetAsync上停止了. (我传递的网址是有效的,并且该网址在不到一秒钟的时间内响应了)

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?

更新/应答

感谢史蒂文,他指出了解决问题的方法.为了确保已定义的答案在那里,下面是修复之前和之后的后台任务:

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:

之前

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

    Update();

    deferral.Complete();
}

public async void Update()
{
    ...
}

之后

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

推荐答案

您必须调用

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

这篇关于HttpClient GetAsync在Windows 8上的后台任务失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆