Windows Phone 8.1 - HttpClient SendRequestAsync will never return with a response

485 views Asked by At

i am trying to receive a response from a HttpClient in Windows Phone 8.1 but it hangs on the method:

httpClient.SendRequestAsync(requestMessage);

The code looks like this:

// Create a client
        var httpClient = new HttpClient();

        // Add a new Request Message
        var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(serviceUri));

        // Add our custom headers
        requestMessage.Headers.Add ("Username", username);
        requestMessage.Headers.Add ("Credential", password);
        requestMessage.Headers.Add ("DBName", databaseName);


        requestMessage.Method = HttpMethod.Get;

        // Send the request to the server
        var response = await httpClient.SendRequestAsync(requestMessage);

        // Just as an example I'm turning the response into a string here
        var token = await response.Content.ReadAsStringAsync();


        return token;

The server receives the header values and returns the token but the HttpClient will no get the answer.

Is there anything wrong in this code?

Thank you for your help!

1

There are 1 answers

1
Stephen Cleary On BEST ANSWER

I suspect that further up your call stack, your code is calling Task<T>.Result or Task.Wait. This will deadlock your application.

The appropriate solution is to replace all calls to Result or Wait with await.

More info in my MSDN article on async best practices or my blog post that deals with this kind of async deadlock in detail.