HttpClient GetAsync在Windows 8上的后台任务中失败

我有一个Win RT应用程序,它有一个后台任务,负责调用API来检索自己需要更新的数据。 但是,我遇到了一个问题; 在后台任务之外运行时,调用API的请求可以正常工作。 在后台任务中,它失败了,并且还隐藏了任何可以帮助指出问题的exception。

我通过调试器跟踪此问题以跟踪问题点,并validation执行在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' { ... } 

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

以下是我这样做的方式,它对我有用

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