在 HttpClient 中使用 await 的异步调用永远不会返回 [英] Async call with await in HttpClient never returns
问题描述
我在 Win8 CP 上的基于 xaml 的 C#
地铁应用程序中进行了调用;这个调用只是访问一个网络服务并返回 JSON 数据.
I have a call I am making from inside a xaml-based, C#
metro application on the Win8 CP; this call simply hits a web service and returns JSON data.
HttpMessageHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
httpClient.BaseAddress = new Uri("http://192.168.1.101/api/");
var result = await httpClient.GetStreamAsync("weeklyplan");
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(WeeklyPlanData[]));
return (WeeklyPlanData[])ser.ReadObject(result);
它挂在 await
处,但 http 调用实际上几乎立即返回(通过 fiddler 确认);就好像 await
被忽略了,它只是挂在那里.
It hangs at the await
but the http call actually returns almost immediately (confirmed through fiddler); it is as if the await
is ignored and it just hangs there.
在您询问之前 - 是的 - 专用网络功能已打开.
Before you ask - YES - the Private Network capability is turned on.
任何想法为什么会挂起?
Any ideas why this would hang?
推荐答案
查看这个答案我的问题,这似乎非常相似.
Check out this answer to my question which seems to be very similar.
尝试一下:对 GetStreamAsync()
返回的任务调用 ConfigureAwait(false)
.例如
Something to try: call ConfigureAwait(false)
on the Task returned by GetStreamAsync()
. E.g.
var result = await httpClient.GetStreamAsync("weeklyplan")
.ConfigureAwait(continueOnCapturedContext:false);
这是否有用取决于你上面的代码是如何被调用的 - 在我的例子中使用 Task.GetAwaiter().GetResult()
调用 async
方法导致代码挂起.
Whether or not this is useful depends on how your code above is being called - in my case calling the async
method using Task.GetAwaiter().GetResult()
caused the code to hang.
这是因为 GetResult()
阻塞当前线程,直到任务完成.当任务完成时,它会尝试重新进入启动它的线程上下文,但无法重新进入,因为该上下文中已经有一个线程,该线程被调用 GetResult()
... 僵局!
This is because GetResult()
blocks the current thread until the Task completes. When the task does complete it attempts to re-enter the thread context in which it was started but cannot because there is already a thread in that context, which is blocked by the call to GetResult()
... deadlock!
这篇 MSDN 帖子详细介绍了如何使用 .NET 同步并行线程 - 并且对我自己问题的回答提供了一些最佳实践.
This MSDN post goes into a bit of detail on how .NET synchronizes parallel threads - and the answer given to my own question gives some best practices.
这篇关于在 HttpClient 中使用 await 的异步调用永远不会返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!