在PCL中与HttpClient进行异步调用

时间:2014-03-26 10:49:08

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

我有一个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;
    }

但等待显示错误“无法等待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;
    }

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

这是截图:

enter image description here

2 个答案:

答案 0 :(得分:6)

关注TAP guidelines,不要忘记致电EnsureSuccessStatusCode,处理您的资源,并将所有Result替换为await s:

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();
  }
}

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

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

答案 1 :(得分:1)

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