Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When doing PostAsync why wait is not working?

In a WebApi project I do a Post to convert some file to another:

var post = client.PostAsync(requestUri, content);
post.Wait();
var result = post.Result;

The result will contain the converted file so is important for me that current Thread to wait for the response before going further and use the result.

Well, it seems that it goes further and of course, the result is not ready yet... Do I do anything wrong here?

like image 536
Cristian Boariu Avatar asked Dec 06 '22 12:12

Cristian Boariu


1 Answers

If you want to do synchronously, needless to call Wait(), just return Result directly, the Result property blocks the calling thread until the task finishes.

var response = client.PostAsync(requestUri, content).Result;
response.EnsureSuccessStatusCode();

In here, the content of result is still not ready yet, you need to continue to get the content:

var responseBody = response.Content.ReadAsStreamAsync().Result;
like image 143
cuongle Avatar answered Jan 02 '23 01:01

cuongle