Async call with HttpClient in PCL

…衆ロ難τιáo~ 提交于 2019-12-11 13:33:40

问题


I have a PCl in which I want to make a async call usingg HttpClient. I coded like this

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

But await is showing error "cannot await System.net.http.httpresponsemessage" like message.

If I use code like this than everything goes well but not in async way

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

I just want that this method executes in async way.

This is the screen shot:


回答1:


Follow the TAP guidelines, don't forget to call EnsureSuccessStatusCode, dispose your resources, and replace all Results with 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();
  }
}

If your code doesn't need to do anything else, HttpClient has a GetStringAsync method that does this for you:

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

If you share your HttpClient instances, this can simplify to:

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



回答2:


If you are using a PCL platform that supports .net4 then I suspect you need to install the Microsoft.bcl.Async nuget.



来源:https://stackoverflow.com/questions/22658632/async-call-with-httpclient-in-pcl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!