HttpClient GetAsync fails in background task on Windows 8
background-process, c#, windows-8, windows-runtime
Solution
You have to call `IBackgroundTaskInterface.GetDeferral` and then call its `Complete` method when your `Task` is complete.
Problem
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. 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? UPDATE/ANSWER 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: Before ``` public void Run(IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); Update(); deferral.Complete(); } public async void Update() { ... } ``` After ``` 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' { ... } ```