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'
{
...
}
GetAsync(Uri, HttpCompletionOption) Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation. GetAsync(Uri, CancellationToken) Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.
Using SendAsync, we can write the code as: static async Task SendURI(Uri u, HttpContent c) { var response = string. Empty; using (var client = new HttpClient()) { HttpRequestMessage request = new HttpRequestMessage { Method = HttpMethod. Post, RequestUri = u, Content = c }; HttpResponseMessage result = await client.
The HTTP request is sent out, and HttpClient. GetAsync returns an uncompleted Task .
You have to call IBackgroundTaskInterface.GetDeferral
and then call its Complete
method when your Task
is complete.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With