gpt4 book ai didi

c# - 在 PCL 中使用 HttpClient 进行异步调用

转载 作者:太空宇宙 更新时间:2023-11-03 18:30:52 25 4
gpt4 key购买 nike

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

我只想让这个方法以异步方式执行。

这是屏幕截图:

enter image description here

最佳答案

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

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

关于c# - 在 PCL 中使用 HttpClient 进行异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22658632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com