大家好
static async Task<Product> GetProductAsync(string path)
{
Product product = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
product = await response.Content.ReadAsAsync<Product>();
}
return product;
}
我在我的代码中使用这个例子,我想知道是否有任何方法可以使用HttpClient
而不使用async/await
,以及我如何才能只获得响应字符串?
提前感谢
是否有任何方法使用HttpClient没有async/await,我怎么能得到只有字符串的响应?
HttpClient
是专门为异步使用而设计的。
如果需要同步下载字符串,请使用WebClient.DownloadString
。
当然可以:
public static string Method(string path)
{
using (var client = new HttpClient())
{
var response = client.GetAsync(path).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
return responseContent.ReadAsStringAsync().GetAwaiter().GetResult();
}
}
}
但正如@MarcinJuraszek所说:
以下是"这可能会导致ASP中的死锁。. NET和WinForms。使用。result或. wait()使用TPL时要谨慎".
WebClient.DownloadString
的示例using (var client = new WebClient())
{
string response = client.DownloadString(path);
if (!string.IsNullOrEmpty(response))
{
...
}
}