C#async等待Task <t>处理

时间:2015-11-12 20:45:43

标签: c# asynchronous async-await

我做了一个httpclient postasync,我想将响应转换为我的模型对象。这是我的代码:

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

因此,此代码是异步处理的。等待处理响应的最佳方法是什么,就在这种情况发生之后继续运行同步代码?

谢谢!

2 个答案:

答案 0 :(得分:2)

“等待”您的帖子调用以打开回复。

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

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

答案 1 :(得分:-1)

我认为您想要做的是将Task存储在变量中,做一些工作,然后等待响应。

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;

或者,如果您有多个异步任务,则可以等待它们,然后处理结果。

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;