【问题标题】:Async call with HttpClient in PCL在 PCL 中使用 HttpClient 进行异步调用
【发布时间】:2014-03-26 10:49:07
【问题描述】:

我有一个 PCl,我想在其中使用 HttpClient 进行异步调用。我是这样编码的

 public static async Task<string> GetRequest(string url)
    {            
        var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
        HttpResponseMessage response = await httpClient.GetAsync(url);
        return response.Content.ReadAsStringAsync().Result;
    }

但 await 显示错误“无法等待 System.net.http.httpresponsemessage”,如消息。

如果我使用这样的代码,一切都会顺利,但不是异步方式

public static string GetRequest(string url)
    {
        var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
        HttpResponseMessage response = httpClient.GetAsync(url).Result;
        return response.Content.ReadAsStringAsync().Result;
    }

我只是希望这个方法以异步方式执行。

这是屏幕截图:

【问题讨论】:

  • “错误”是什么意思:编译错误还是运行时异常?确切的错误信息是什么?
  • 请显示准确错误信息。我敢肯定这不仅仅是“无法等待”。
  • 我更新了我的问题
  • 这在 linqpad 中运行良好

标签: c# asynchronous portable-class-library dotnet-httpclient


【解决方案1】:

关注TAP guidelines,别忘了拨打EnsureSuccessStatusCode,处置资源,将所有Results替换为awaits:

public static async Task<string> GetRequestAsync(string url)
{            
  using (var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue })
  {
    HttpResponseMessage response = await httpClient.GetAsync(url);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsStringAsync();
  }
}

如果您的代码不需要执行任何其他操作,HttpClient 有一个 GetStringAsync 方法可以为您执行此操作:

public static async Task<string> GetRequestAsync(string url)
{            
  using (var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue })
    return await httpClient.GetStringAsync(url);
}

如果您共享您的 HttpClient 实例,这可以简化为:

private static readonly HttpClient httpClient =
    new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
public static Task<string> GetRequestAsync(string url)
{            
  return httpClient.GetStringAsync(url);
}

【讨论】:

  • @ta.speot.is:已回复here
  • @ta.speot.is 当以这种方式使用时,是的,它应该被处理掉。但是,为每个请求创建一个新实例并不是使用 HttpClient 的最佳方式。
  • 已更新以正确处理资源。
  • @StephenCleary 我在使用您的代码时遇到同样的错误,请检查问题的更新部分。
  • @mayank.karki:安装Microsoft.Bcl.Async NuGet 包。
【解决方案2】:

如果您使用的是支持 .net4 的 PCL 平台,那么我怀疑您需要安装 Microsoft.bcl.Async nuget。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多