HttpClient.GetAsync(…)使用等待/异步时永不返回我在.NET 4.5中使用System.Net.Http.HttpClient遇到了一些奇怪的行为,其中“等待”调用(例如)的结果。httpClient.GetAsync(...)再也不会回来了。这种情况只有在使用新的异步/等待语言功能和任务API时才会发生-当只使用连续时,代码似乎总是有效的。下面是一些再现问题的代码-将其放到VisualStudio 11中的一个新的“MVC 4 WebApi项目”中,以公开以下GET端点:/api/test1/api/test2/api/test3/api/test4/api/test5 <--- never completes/api/test6这里的每个端点都返回相同的数据(stackoverflow.com中的响应头),但/api/test5永远不会结束。我是否在HttpClient类中遇到了一个bug,或者我是否在某种程度上误用了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;
}}
3 回答
- 3 回答
- 0 关注
- 6814 浏览
添加回答
举报
0/150
提交
取消