HttpClient的GetAsync未能在后台任务在Windows 8(HttpClient Ge

2019-07-02 15:24发布

我有了负责调用API来检索它需要更新自身数据的后台任务一个双赢RT应用程序。 不过,我碰到的一个问题; 当后台任务之外运行调用API请求完美的作品。 里面的后台任务的,它失败,也隐藏任何异常,可以帮助一点的问题。

我通过调试器跟踪这个问题跟踪问题点,并验证执行上GetAsync停止。 (我传递的URL是有效的,而URL中不到一秒钟的响应)

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

我读过的所有文档中说,一个后台任务被允许,因为它需要有尽可能多的网络流量(节流当然)。 所以,我不明白为什么这会失败,或知道任何其他方式来诊断问题。 我在想什么?


UPDATE / ANSWER

感谢史蒂芬,他指明了方向的问题。 在确保定义的答案就在那里,利益在这里是后台任务前和修复程序后:

之前

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

Answer 1:

你必须调用IBackgroundTaskInterface.GetDeferral ,然后调用其Complete方法时,你的Task就完成了。



Answer 2:

以下是我在做它的方式和它的作品对我来说

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


文章来源: HttpClient GetAsync fails in background task on Windows 8