HttpClient.GetAsync(...)在使用等待/异步时从不返回(HttpClient.GetAsync(…) never returns when using await/async)

编辑: 这个问题看起来可能是同一个问题,但没有回应...

编辑:在测试用例5中,任务似乎被卡在WaitingForActivation状态。

我使用.NET 4.5中的System.Net.Http.HttpClient遇到了一些奇怪的行为 - 其中“等待”调用结果(例如) httpClient.GetAsync(...)将永远不会返回。

这仅在使用新的异步/等待语言功能和Tasks API的某些情况下发生 - 代码总是似乎在仅使用延续时才起作用。

以下是一些重现问题的代码 - 将其放入Visual Studio 11中的一个新的“MVC 4 WebApi项目”,以显示以下GET端点:

/api/test1
/api/test2
/api/test3
/api/test4
/api/test5 <--- never completes
/api/test6

这里的每个端点返回相同的数据(来自stackoverflow.com的响应头),除了/api/test5 ,从未完成。

我在HttpClient类中遇到了错误,还是以某种方式滥用API?

复制代码:

public class BaseApiController : ApiController
{
    /// <summary>
    /// Retrieves data using continuations
    /// </summary>
    protected Task<string> Continuations_GetSomeDataAsync()
    {
        var httpClient = new HttpClient();

        var t = httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead);

        return t.ContinueWith(t1 => t1.Result.Content.Headers.ToString());
    }

    /// <summary>
    /// Retrieves data using async/await
    /// </summary>
    protected async Task<string> AsyncAwait_GetSomeDataAsync()
    {
        var httpClient = new HttpClient();

        var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead);

        return result.Content.Headers.ToString();
    }
}

public class Test1Controller : BaseApiController
{
    /// <summary>
    /// Handles task using Async/Await
    /// </summary>
    public async Task<string> Get()
    {
        var data = await Continuations_GetSomeDataAsync();

        return data;
    }
}

public class Test2Controller : BaseApiController
{
    /// <summary>
    /// Handles task by blocking the thread until the task completes
    /// </summary>
    public string Get()
    {
        var task = Continuations_GetSomeDataAsync();

        var data = task.GetAwaiter().GetResult();

        return data;
    }
}

public class Test3Controller : BaseApiController
{
    /// <summary>
    /// Passes the task back to the controller host
    /// </summary>
    public Task<string> Get()
    {
        return Continuations_GetSomeDataAsync();
    }
}

public class Test4Controller : BaseApiController
{
    /// <summary>
    /// Handles task using Async/Await
    /// </summary>
    public async Task<string> Get()
    {
        var data = await AsyncAwait_GetSomeDataAsync();

        return data;
    }
}

public class Test5Controller : BaseApiController
{
    /// <summary>
    /// Handles task by blocking the thread until the task completes
    /// </summary>
    public string Get()
    {
        var task = AsyncAwait_GetSomeDataAsync();

        var data = task.GetAwaiter().GetResult();

        return data;
    }
}

public class Test6Controller : BaseApiController
{
    /// <summary>
    /// Passes the task back to the controller host
    /// </summary>
    public Task<string> Get()
    {
        return AsyncAwait_GetSomeDataAsync();
    }
}

Edit: This question looks like it might be the same problem, but has no responses...

Edit: In test case 5 the task appears to be stuck in WaitingForActivation state.

I've encountered some odd behaviour using the System.Net.Http.HttpClient in .NET 4.5 - where "awaiting" the result of a call to (e.g.) httpClient.GetAsync(...) will never return.

This only occurs in certain circumstances when using the new async/await language functionality and Tasks API - the code always seems to work when using only continuations.

Here's some code which reproduces the problem - drop this into a new "MVC 4 WebApi project" in Visual Studio 11 to expose the following GET endpoints:

/api/test1
/api/test2
/api/test3
/api/test4
/api/test5 <--- never completes
/api/test6

Each of the endpoints here return the same data (the response headers from stackoverflow.com) except for /api/test5 which never completes.

Have I encountered a bug in the HttpClient class, or am I misusing the API in some way?

Code to reproduce:

public class BaseApiController : ApiController
{
    /// <summary>
    /// Retrieves data using continuations
    /// </summary>
    protected Task<string> Continuations_GetSomeDataAsync()
    {
        var httpClient = new HttpClient();

        var t = httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead);

        return t.ContinueWith(t1 => t1.Result.Content.Headers.ToString());
    }

    /// <summary>
    /// Retrieves data using async/await
    /// </summary>
    protected async Task<string> AsyncAwait_GetSomeDataAsync()
    {
        var httpClient = new HttpClient();

        var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead);

        return result.Content.Headers.ToString();
    }
}

public class Test1Controller : BaseApiController
{
    /// <summary>
    /// Handles task using Async/Await
    /// </summary>
    public async Task<string> Get()
    {
        var data = await Continuations_GetSomeDataAsync();

        return data;
    }
}

public class Test2Controller : BaseApiController
{
    /// <summary>
    /// Handles task by blocking the thread until the task completes
    /// </summary>
    public string Get()
    {
        var task = Continuations_GetSomeDataAsync();

        var data = task.GetAwaiter().GetResult();

        return data;
    }
}

public class Test3Controller : BaseApiController
{
    /// <summary>
    /// Passes the task back to the controller host
    /// </summary>
    public Task<string> Get()
    {
        return Continuations_GetSomeDataAsync();
    }
}

public class Test4Controller : BaseApiController
{
    /// <summary>
    /// Handles task using Async/Await
    /// </summary>
    public async Task<string> Get()
    {
        var data = await AsyncAwait_GetSomeDataAsync();

        return data;
    }
}

public class Test5Controller : BaseApiController
{
    /// <summary>
    /// Handles task by blocking the thread until the task completes
    /// </summary>
    public string Get()
    {
        var task = AsyncAwait_GetSomeDataAsync();

        var data = task.GetAwaiter().GetResult();

        return data;
    }
}

public class Test6Controller : BaseApiController
{
    /// <summary>
    /// Passes the task back to the controller host
    /// </summary>
    public Task<string> Get()
    {
        return AsyncAwait_GetSomeDataAsync();
    }
}

原文:https://stackoverflow.com/questions/10343632
2023-08-19 09:08

满意答案

尝试像这样格式化导入(而不是在媒体查询中):

@import url(foo.css) screen and (min-width:320px);
@import url(bar.css) screen and (min-device-width:768px) and (orientation:portrait);
@import url(blah.css) screen and (min-device-width:768px) and (orientation:landscape);

Try formatting your imports like this (instead of inside a media query):

@import url(foo.css) screen and (min-width:320px);
@import url(bar.css) screen and (min-device-width:768px) and (orientation:portrait);
@import url(blah.css) screen and (min-device-width:768px) and (orientation:landscape);

相关问答

更多

定向平板电脑与手机(orientation tablet vs phone)

阅读这篇文章: http : //android-developers.blogspot.com/2010/09/one-screen-turn-deserves-another.html 此外,请勿在活动可见时使用唤醒锁定以保持屏幕开启。 改为在视图上使用KEEP_SCREEN_ON标志,您可以删除唤醒锁定权限。 Read this post: http://android-developers.blogspot.com/2010/09/one-screen-turn-deserves-anot...

如何使用媒体查询分离手机与平板电脑肖像与平板电脑景观(how to use media query to seperate phone vs tablet portrait vs tablet landscape)

尝试像这样格式化导入(而不是在媒体查询中): @import url(foo.css) screen and (min-width:320px); @import url(bar.css) screen and (min-device-width:768px) and (orientation:portrait); @import url(blah.css) screen and (min-device-width:768px) and (orientation:landscape); Try ...

媒体查询:如何定位桌面,平板电脑和手机?(Media Queries: How to target desktop, tablet and mobile?)

IMO这些是最好的断点: @media (min-width:320px) { /* smartphones, portrait iPhone, portrait 480x320 phones (Android) */ } @media (min-width:480px) { /* smartphones, Android phones, landscape iPhone */ } @media (min-width:600px) { /* portrait tablets, portrai...

如何检测React Native上的平板电脑风景(How detect tablet landscape on React Native)

其他答案已经解决了屏幕检测任务。 但是,仍然存在检测代码是否在Tablet设备上运行的问题。 您可以使用react-native-device-info包检测它,特别是它的isTablet方法。 因此,作为示例,在您的组件中: constructor(){ super(); this.state = {orientation: 'UNKNOWN'} this._onOrientationChanged = this._onOrientationChanged.bind(this); }...

iOS / Android Phonegap - 智能手机的肖像,平板电脑上的风景(iOS/Android Phonegap - portrait for smartphones, landscape on tablets)

您可以使用navigator.userAgent来获取设备类型。 例如这样的事情: var deviceType = (navigator.userAgent.match(/iPad/i)) == "iPad" ? "iPad" : (navigator.userAgent.match(/iPhone/i)) == "iPhone" ? "iPhone" : (navigator.userAgent.match(/Android/i)) == "Android" ? "Android" : (...

整洁2.0平板电脑媒体查询不起作用(Neat 2.0 tablet media query not working)

我认为问题在于您的SCSS对于平板电脑部分略有不同。 尝试这个: $tablet: ( columns: 12, gutter: 1.1em, media: 'screen and (min-width 768px) and (max-width 1024px)' ); I think the issue is that your SCSS is slightly wrong for the tablet section. Try this: $tablet: ( columns: 12...

Android平板电脑横向和纵向模式(Android Tablet Landscape and Portrait Modes)

不是正统的方式,但你可以像这样实现它,创建2个资源文件一个通用,一个用于sw600dp(平板电脑)并添加一个bool“istablet” 然后在你的活动OnCreate方法 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(!getResources().getBoolean(R.bool.is...

如何在风景mdoe手机上运行我的Android平板电脑应用程序时看起来一样(How can I make my android tablet app to look the same when it runs on phone in landscape mdoe)

我认为你需要使用2个标志,而不仅仅是一个。 首先是 android:screenOrientation='landscape' 第二是 android:configChanges="orientation" 首先会告诉android在横向模式下运行活动,其中第二个将告诉android即使用户旋转手机也不会改变方向。 基本上使用第二个标志,您将覆盖方向配置更改。 I think you need to use 2 flags, not just one. First is android:sc...

开发通用的Android应用程序(手机和平板电脑) - 定义方向(Developing an universal android application (phone and tablet) - Defining Orientations)

我相信你可以在res / layout文件夹中创建一个子文件夹,名为xlarge-land和xlarge-port,其中包含xml文件。 设备本身将知道要加载什么xml。 res/layout/my_layout.xml // layout for normal screen size ("default") res/layout-small/my_layout.xml // layout for small screen size res/layout-lar...

针对目标移动设备(第一),平板电脑和桌面的特定媒体查询(Specific media queries for target mobile (first), tablet & desktop)

使用Modernizr( http://modernizr.com/download/ )检测触摸设备。 Modernizr会将.touch或.no-touch类添加到您的html标签中。 因此,对于桌面,您将使用.touch类来定位桌面。 @media only screen and (min-width: 960px) { .touch .container { width: 960px; } } Use Modernizr (http://modernizr.com/downloa...

相关文章

更多

关于多线程问题,signalAll,await问题

package ThreadTest; import java.util.concurrent.Tim ...

微信公众平台.net HttpClient 异步客户端

微信公众平台.net HttpClient 异步客户端 该客户端实现了对微信公众平台的后台管理,包括 ...

httpclient get请求

httpclient get进行get请求步骤: 1、创建Httpclient对象 HttpCli ...

Windows Phone 获取app在商店中的版本(检查app的版本号)

public classAppVersionHelper { /// &lt;summary ...

httpClient快速入门

本示例是基于HttpClient 4.3,示例比较简单,就是请求http://www.656463.c ...

httpclient post 请求

httpclient post请求与get请求的区别主要是httpclient.execute对象 ...

HttpClient DELETE请求示例

本教程演示如何使用Apache HttpClient 4.5创建Http DELETE请求。 HTTP ...

HttpClient CacheConfig缓存处理示例

是如何设置基本缓存HttpClient的简单示例。 按照配置,它将存储最多3000个缓存对象,其中每个 ...

httpclient 带参数 get 请求

httpclient带参数get请求和默认get请求的主要区别是要初始化HttpGet的方式 默认的g ...

Httpclient整合Spring教程

Httpclient和Spring的整合就是把直接new对象的方式改为spring配置即可 1、首先 ...

最新问答

更多

python的访问器方法有哪些

使用方法: class A(object): def foo(self,x): #类实例方法 print "executing foo(%s,%s)"%(self,x) @classmethod def class_foo(cls,x): #类方法 print "executing class_foo(%s,%s)"%(cls,x) @staticmethod def static_foo(x): #静态方法 print "executing static_foo(%s)"%x调用方法: a =

使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)

我认为你必须将两个TableGetway传递给UserTable构造。 你必须改变Module.php看看: public function getServiceConfig() { return array( 'factories' => array( 'User\Model\UserTable' => function($sm) { $userTableGateway = $sm->get('UserTable

透明度错误IE11(Transparency bug IE11)

这是一个渲染错误,由使用透明度触发,使用bootstrap用于在聚焦控件周围放置蓝色光环的box-shadow属性。 可以通过添加以下类覆盖来解决它。 .form-control:hover { -webkit-box-shadow: 0px 0px 5px 0px rgba(0,0,255,1); -moz-box-shadow: 0px 0px 5px 0px rgba(0,0,255,1); box-shadow: 0px 0px 4px 0px rgba(0,0,255,1)

linux的基本操作命令。。。

ls 显示目录 mkdir 建立目录 cd 进入目录

响应navi重叠h1和nav上的h1链接不起作用(Responsive navi overlaps h1 and navi links on h1 isn't working)

将z-index设置为.main-nav这将解决您的重叠问题 .main-nav { position:relative; z-index:9; } set z-index to .main-nav This will fix your overlaping issue .main-nav { position:relative; z-index:9; }

在C中读取文件:“r”和“a +”标志的不同行为(Reading a File in C: different behavior for “r” and “a+” flags)

这是因为模式规范"a"打开一个文件以便追加,文件指针在末尾。 如果您尝试从此处读取,则由于文件指针位于EOF,因此没有数据。 您应该打开"r+"进行阅读和写作。 如果在写入之前读取整个文件,则在写入更多数据时,文件指针将正确定位以追加。 如果这还不够,请探索ftell()和fseek()函数。 That is because the mode spec "a" opens a file for appending, with the file pointer at the end. If you

NFC提供什么样的带宽?(What Kind of Bandwidth does NFC Provide?)

支持空中接口的数据速率是一回事。 在消除协议开销,等待eeprom写入以及所有需要时间的其他内容之后,您看到的数据速率是完全不同的故事。 长话短说,从标签读取或进行对等传输时的实际数据速率峰值约为2.5千字节/秒。 取决于具体的标签或对等技术,它可能比这慢很多。 The supported data-rates of the air-interface are one thing. The data-rate that you see after removing protocol overhe

元素上的盒子阴影行为(box-shadow behaviour on elements)

它看起来像只在Windows上的Chrome的错误。 我在Google Canary (Chrome 63)中也进行了测试,问题依然存在,所以有可能它不会很快修复。 这个问题是由overflow: auto引起的overflow: auto ,在你的情况下,它可以很容易地通过删除或设置为可见(默认)来解决。 但是 ,将鼠标悬停在右侧(顶部和底部)时,会出现滚动条。 一个解决方案可以设置overflow: hidden的身体,所以预期的结果是所需的。 我想指出,这不是一个很好的解决方案,但我建议暂

Laravel检查是否存在记录(Laravel Checking If a Record Exists)

这取决于您是否要以后与用户合作,或仅检查是否存在。 如果要使用用户对象(如果存在): $user = User::where('email', '=', Input::get('email'))->first(); if ($user === null) { // user doesn't exist } 如果你只想检查 if (User::where('email', '=', Input::get('email'))->count() > 0) { // user found

设置base64图像的大小javascript - angularjs(set size of a base64 image javascript - angularjs)

$scope.getData= function () { var reader = new FileReader(); reader.onload = $('input[type=file]')[0].files; var img = new Image(); img.src =(reader.onload[0].result); img.onload = function() { if(this.width > 640