在HttpClient的永远不会返回异步调用带的await [英] Async call with await in HttpClient never returns

查看:1032
本文介绍了在HttpClient的永远不会返回异步调用带的await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个电话,我从上的Win8 CP基于XAML的, C# Metro应用内决策;此调用只需打一个Web服务,并返回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 的调用实际上几乎立即返回(通过小提琴手确认);这是因为如果在等待被忽略,它只是挂在那里。

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.

一些尝试:呼叫 ConfigureAwait(假)返回的任务GetStreamAsync()。例如。

Something to try: call ConfigureAwait(false) on the Task returned by GetStreamAsync(). E.g.

var result = await httpClient.GetStreamAsync("weeklyplan")
                             .ConfigureAwait(continueOnCapturedContext:false);

不管这是非常有用取决于如何你的code以上的被称为 - 在我的情况下调用异步使用方法任务.GetAwaiter()调用getResult()引起了code挂起。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆