Async is waiting for an HttpClient.PostAsync call

I am trying to transfer a call to PostAsync, so I do not need to recode the sequence of calls throughout my code base. The problem I am facing is that the HttpResponseMessage that I assigned from the call does not match the one that the consumer of my method calls. Here is the code:

internal class RestHttpClient { public HttpResponseMessage ResponseMessage = new HttpResponseMessage(); public async void SendRequest(string adaptiveUri, string xmlRequest) { using (HttpClient httpClient = new HttpClient()) { StringContent httpConent = new StringContent(xmlRequest, Encoding.UTF8); try { ResponseMessage = await httpClient.PostAsync(adaptiveUri, httpConent); } catch (Exception ex) { ResponseMessage.StatusCode = HttpStatusCode.InternalServerError; ResponseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex); } } } } 

And I am trying to call the method as follows:

 RestHttpClient restHttpClient = new RestHttpClient(); restHttpClient.SendRequest(adaptiveUri, xmlRequest); return restHttpClient.ResponseMessage; 

When I make a call, the ResponseMessage object always contains the status Ok, even if it is not something that is actually returned from the PostAsync call.

+5
source share
1 answer

The reason you see this is because your async void method runs in fire and swell mode, so you see the value returned by setting the response message, not the PostAsync response.

Do not expose one class HttpResponseMessage , it may be deprecated if it is called simultaneously in the same instance. Instead, return a new instance each time:

 public async Task<HttpResponseMessage> SendRequestAsync(string adaptiveUri, string xmlRequest) { using (HttpClient httpClient = new HttpClient()) { StringContent httpConent = new StringContent(xmlRequest, Encoding.UTF8); HttpResponseMessage responseMessage = null; try { responseMessage = await httpClient.PostAsync(adaptiveUri, httpConent); } catch (Exception ex) { if (responseMessage == null) { responseMessage = new HttpResponseMessage(); } responseMessage.StatusCode = HttpStatusCode.InternalServerError; responseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex); } return responseMessage; } } 

And when you call it, correctly await it:

 return await restHttpClient.SendRequestAsync(adaptiveUri, xmlRequest); 
+12
source

All Articles