简体   繁体   中英

C# async wait for Task<T> to process

I make a httpclient postasync and I want to convert the response to my model object. This is my code:

var response = client.PostAsync(TERMBASED_ENDPOINT,
    new StringContent(JsonConvert.SerializeObject(request).ToString(),
                      Encoding.UTF8, "application/json")).Result;

var result = await response.Content.ReadAsAsync<MyObject>();
//other code synchronously processed

So, this code is asynchronously processed. What is the best method to wait for the response to be processed and just after this happens to continue to run the synchronous code??

Thank you!

"await" your post call to unwrap the response.

var response = await client.PostAsync(TERMBASED_ENDPOINT,
    new StringContent(JsonConvert.SerializeObject(request).ToString(),
                      Encoding.UTF8, "application/json"));

var result = JsonConvert.DeserializeObject<MyObject>(response.Content);

I think what you are wanting to do is store the Task in a variable, do some work, and then await the response.

var response = client.PostAsync(TERMBASED_ENDPOINT,
    new StringContent(JsonConvert.SerializeObject(request).ToString(),
                      Encoding.UTF8, "application/json")).Result;

var readTask = response.Content.ReadAsAsync<MyObject>();
//other code synchronously processed
var result = await readTask;

Alternatively, if you have several asynchronous tasks you can wait for them all and then process the results.

var response = client.PostAsync(TERMBASED_ENDPOINT,
    new StringContent(JsonConvert.SerializeObject(request).ToString(),
                      Encoding.UTF8, "application/json")).Result;

var readTask = response.Content.ReadAsAsync<MyObject>();
//other code synchronously processed
await Task.WhenAll(readTask);
var result = readTask.Result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM