Mik*_*rds 10 c# background-process windows-8 windows-runtime
我有一个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);
}
Run Code Online (Sandbox Code Playgroud)
我读过的所有文档都说允许后台任务拥有所需的网络流量(当然会受到限制).所以,我不明白为什么会失败,或者知道任何其他方法来诊断问题.我错过了什么?
UPDATE/ANSWER
感谢史蒂文,他指出了解决问题的方法.在确保定义的答案就在那里,利益在这里是后台任务前和修复程序后:
之前
public void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
Update();
deferral.Complete();
}
public async void Update()
{
...
}
Run Code Online (Sandbox Code Playgroud)
后
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'
{
...
}
Run Code Online (Sandbox Code Playgroud)