在PCL异步调用与HttpClient的(Async call with HttpClient in

2019-10-19 15:59发布

我有我想要做一个异步调用usingg的HttpClient了PCL。 我编写这样的

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

我只是想,这种方法在异步的方式执行。

这是屏幕截图:

Answer 1:

按照TAP准则 ,不要忘记调用EnsureSuccessStatusCode ,处置您的资源,并更换所有Result s的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);
}


Answer 2:

如果您使用的是支持.NET4一个PCL平台,然后我怀疑你需要安装Microsoft.bcl.Async的NuGet。



文章来源: Async call with HttpClient in PCL