Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient GetAsync fails in background task on Windows 8

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'
{
    ...
}
like image 429
Mike Richards Avatar asked Oct 25 '12 23:10

Mike Richards


People also ask

What is HttpClient GetAsync?

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.

How do I use HttpClient GetAsync?

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.

What does HttpClient GetAsync return?

The HTTP request is sent out, and HttpClient. GetAsync returns an uncompleted Task .


1 Answers

You have to call IBackgroundTaskInterface.GetDeferral and then call its Complete method when your Task is complete.

like image 165
Stephen Cleary Avatar answered Oct 09 '22 13:10

Stephen Cleary