gpt4 book ai didi

c# - HttpClient GetAsync 在 Windows 8 的后台任务中失败

转载 作者:可可西里 更新时间:2023-11-01 09:08:14 25 4
gpt4 key购买 nike

我有一个 Win RT 应用程序,它有一个后台任务负责调用 API 来检索它需要更新自身的数据。但是,我遇到了一个问题;在后台任务之外运行时,调用 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);
}

我读过的所有文档都说后台任务可以根据需要拥有尽可能多的网络流量(当然会受到限制)。所以,我不明白为什么这会失败,或者不知道任何其他诊断问题的方法。我错过了什么?


更新/回答

感谢 Steven,他指出了解决问题的方法。为了确保定义的答案在那里,这里是修复前后的后台任务:

之前

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 方法。

关于c# - HttpClient GetAsync 在 Windows 8 的后台任务中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13078635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com