在PCL中与HttpClient进行异步调用

may*_*rki 1 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;
    }
Run Code Online (Sandbox Code Playgroud)

但等待显示错误"无法等待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;
    }
Run Code Online (Sandbox Code Playgroud)

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

这是屏幕截图:

在此输入图像描述

Ste*_*ary 6

遵循TAP指南,不要忘记致电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();
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您的代码不需要执行任何其他操作,请使用HttpClient一种GetStringAsync方法为您执行此操作:

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

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

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