Async call with await in HttpClient never returns

async-await, asynchronous, c#, dotnet-httpclient

Solution

Check out this answer to my question which seems to be very similar.

Something to try: call `ConfigureAwait(false)` on the Task returned by `GetStreamAsync()`. E.g.

var result = await httpClient.GetStreamAsync("weeklyplan")
                             .ConfigureAwait(continueOnCapturedContext:false);

Whether or not this is useful depends on how your code above is being called - in my case calling the `async` method using `Task.GetAwaiter().GetResult()` caused the code to hang.

This is because `GetResult()` blocks the current thread until the Task completes. When the task does complete it attempts to re-enter the thread context in which it was started but cannot because there is already a thread in that context, which is blocked by the call to `GetResult()`... deadlock!

This MSDN post goes into a bit of detail on how .NET synchronizes parallel threads - and the answer given to my own question gives some best practices.

Problem

I have a call I am making from inside a xaml-based, `C#` metro application on the Win8 CP; this call simply hits a web service and returns JSON data. ``` HttpMessageHandler handler = new HttpClientHandler(); HttpClient httpClient = new HttpClient(handler); httpClient.BaseAddress = new Uri("http://192.168.1.101/api/"); var result = await httpClient.GetStreamAsync("weeklyplan"); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(WeeklyPlanData[])); return (WeeklyPlanData[])ser.ReadObject(result); ``` It hangs at the `await` but the http call actually returns almost immediately (confirmed through fiddler); it is as if the `await` is ignored and it just hangs there. Before you ask - YES - the Private Network capability is turned on. Any ideas why this would hang?

Original source

Related problems