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

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
更新时间:2024-04-23 12:04

最满意答案

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

@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);

相关问答

更多

相关文章

更多

最新问答

更多
  • CSS修复容器和溢出元素(CSS Fix container and overflow elements)
  • SQL多个连接在与where子句相同的表上(SQL Multiple Joins on same table with where clause)
  • nginx 80端口反向代理多个域名,怎样隐藏端口的
  • xcode提醒样式,swift 3(xcode alert style, swift 3)
  • 在Chrome控制台中调试JavaScript(debugging javascript in Chrome console)
  • Javascript - 试图围绕自定义事件(Javascript - Trying to wrap my head around custom events)
  • 边栏链接不可点击(Sidebar links aren't clickable)
  • 使用recpatcha gem时如何显示其他表单错误?(How do I display other form errors when using the recpatcha gem?)
  • boost.python避免两次注册内部类,但仍然在python中公开(boost.python Avoid registering inner class twice but still expose in python)
  • Android 现在软件很少吗?以后会多起来吗
  • 如何在ActiveAdmin 0.5.0中为资源全局指定预先加载?(How to specify eager loading globally for a resource in ActiveAdmin 0.5.0?)
  • matlab代码为黄金比例持续分数(matlab code for golden ratio continued fraction)
  • Android浏览器触摸事件位置(Android browser touch event location)
  • 将cURL输出分配给Bash中的变量(Assign output to variable in Bash)
  • 我如何在MVC视图上没有时间获取当前日期(how i can get current date without time on MVC view)
  • sql连接函数(sql join of function)
  • 为什么在Xamarin Media插件中使用ImageSource.FromStream而不是FromFile?(Why use ImageSource.FromStream instead of FromFile in Xamarin Media plugin?)
  • 这段代码是否真的可以防止SQL注入?(Will this code actually work against SQL-injection? [duplicate])
  • 信阳方远计算机学校大专证被国家认可么
  • React / Rails AJAX POST请求返回404(React/Rails AJAX POST request returns 404)
  • Android与php服务器交互(Android interact with php server)
  • 自动刷新QTableWidget可能吗?(Refresh QTableWidget automatically possible?)
  • JVM / Compiler优化对象的未使用属性(optimization of unused properties of object by JVM / Compiler)
  • 插入表格时,乌克兰字符会更改为问号(Ukrainian character change to question mark when insert to table)
  • 在头文件中包含异常类(Including an exception class in a header file)
  • 完成c#中的执行后关闭sqlcmd(Close sqlcmd after finishing executing in c#)
  • 使用软导航栏正确检测屏幕尺寸(Detecting screensize correctly with soft navigation bar)
  • Typescript:从输入更新值(Typescript : update value from input)
  • 如何在执行某些行后仅在断点处停止?(How to only stop at a breakpoint after some line was executed?)
  • 以未定义的元素在JSON中循环(loop in JSON with undefined elements)