2

I wonder if this code works as expected (send a string to a web application):

using (HttpClient httpClient = Util.CreateHttpClient()) { httpClient.PostAsJsonAsync("theurl", somestr); } 

Since PostAsJsonAsync doesn't complete execution immediately, and httpClient is disposed when exiting the block, is the request always sent properly?

Or do I have to wait for the task like this:

using (HttpClient httpClient = Util.CreateHttpClient()) { httpClient.PostAsJsonAsync("theurl", somestr).Wait(); } 

2 Answers 2

2

When using the asynchronous API of HttpClient, its recommended you await these methods:

using (HttpClient httpClient = Util.CreateHttpClient()) { await httpClient.PostAsJsonAsync("theurl", somestr); } 

That way, you ensure completion of the asynchronous method and you make sure HttpClient isn't disposed until the request is sent.

If you need a synchronous API, consider looking at WebClient.

Sign up to request clarification or add additional context in comments.

Comments

0

You have to wait or keep the client in scope.

1 Comment

Do you have a source for this?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.