调用 Async WebAPI 后,控制不会返回到等待的 webClient
Control does not come back to the awaited webClient after calling Async WebAPI
我们有一个 Restful 客户端-服务器环境,我正在尝试调试我的代码,客户端代码如下所示:
await Client.DoWork(Id);
虽然服务器代码如下所示:
public virtual async Task<IActionResult> DoWork(long Id)
{
return Ok();
}
请注意,客户端是从 https://github.com/swagger-api/swagger-codegen
代码自动生成的服务的网络客户端。
自动生成的代码中永远不会返回的点如下所示:
var response_ = await client_.SendAsync(request_,
System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
cancellationToken).ConfigureAwait(false);
这就是控件消失的地方
- 有一件事在这里可能有帮助也可能没有帮助,那就是服务调用是通过代理进行的。不确定这是否会改变什么
当客户端调用 API 时,我可以看到它转到 Return OK()
并且我在 Fiddler 中看到它确实 return 200OK 但控制永远不会返回到调用方法。我该如何解决这个问题?
您已经发现将 .Wait()
添加到控制台应用程序中的异步方法可以解决问题。 How Async and Await works. And the article mentioned in the answer Async and Await.
上有一个很好的答案
When the await operator is passed an incomplete task ... then by default await will capture the current context and return an incomplete task from the method.
所以基本上当客户端开始与服务器方法进行异步通信时 returns 未完成的任务。并且因为在 Main
方法中没有等待它,所以在客户端从服务器获得响应之前控制台应用程序退出。
控制台应用程序中没有 SynchronizationContext
,因此可以安全地使用 .Wait()
方法或 .Result
属性 来阻塞 Main
方法中的线程,直到异步操作完成。
我们有一个 Restful 客户端-服务器环境,我正在尝试调试我的代码,客户端代码如下所示:
await Client.DoWork(Id);
虽然服务器代码如下所示:
public virtual async Task<IActionResult> DoWork(long Id)
{
return Ok();
}
请注意,客户端是从 https://github.com/swagger-api/swagger-codegen
代码自动生成的服务的网络客户端。
自动生成的代码中永远不会返回的点如下所示:
var response_ = await client_.SendAsync(request_,
System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
cancellationToken).ConfigureAwait(false);
这就是控件消失的地方
- 有一件事在这里可能有帮助也可能没有帮助,那就是服务调用是通过代理进行的。不确定这是否会改变什么
当客户端调用 API 时,我可以看到它转到 Return OK()
并且我在 Fiddler 中看到它确实 return 200OK 但控制永远不会返回到调用方法。我该如何解决这个问题?
您已经发现将 .Wait()
添加到控制台应用程序中的异步方法可以解决问题。 How Async and Await works. And the article mentioned in the answer Async and Await.
When the await operator is passed an incomplete task ... then by default await will capture the current context and return an incomplete task from the method.
所以基本上当客户端开始与服务器方法进行异步通信时 returns 未完成的任务。并且因为在 Main
方法中没有等待它,所以在客户端从服务器获得响应之前控制台应用程序退出。
控制台应用程序中没有 SynchronizationContext
,因此可以安全地使用 .Wait()
方法或 .Result
属性 来阻塞 Main
方法中的线程,直到异步操作完成。