在做PostAsync时为什么等待不起作用?

Cri*_*riu 3 asp.net-mvc asp.net-web-api

在WebApi项目中,我做一个Post将一些文件转换为另一个文件:

var post = client.PostAsync(requestUri, content);
post.Wait();
var result = post.Result;
Run Code Online (Sandbox Code Playgroud)

结果将包含转换后的文件,因此对我来说重要的是当前的Thread要等待响应才能进一步使用结果.

好吧,它似乎更进一步,当然,结果尚未准备好......我在这里做错了吗?

cuo*_*gle 7

如果你想同步执行,不用调用Wait(),只需直接返回Result,该Result属性就会阻塞调用线程,直到任务完成.

var response = client.PostAsync(requestUri, content).Result;
response.EnsureSuccessStatusCode();
Run Code Online (Sandbox Code Playgroud)

在这里,结果的内容还没有准备好,你需要继续获取内容:

var responseBody = response.Content.ReadAsStreamAsync().Result;
Run Code Online (Sandbox Code Playgroud)


Six*_*aez 5

我看到Cuong推荐的方法会出现间歇性线程问题。相反,我建议您使用这种方法:

var response = client
      .PostAsync(requestUri, content)
      .ContinueWith( responseTask => {
           var result = responseTask.Result;
           // .... continue with your logic ...
       });

response.Wait();
Run Code Online (Sandbox Code Playgroud)

ContinueWith方法的目的是保证你的代码将再次在原任务完成或中止运行。