C# 如何在没有异步的情况下使用HttpClient
你好,我是下面的C# 如何在没有异步的情况下使用HttpClient,c#,asp.net,asp.net-mvc,webclient,C#,Asp.net,Asp.net Mvc,Webclient,你好,我是下面的 静态异步任务GetProductAsync(字符串路径) { Product=null; HttpResponseMessage response=wait client.GetAsync(路径); if(响应。IsSuccessStatusCode) { product=wait response.Content.ReadAsAsync(); } 退货产品; } 我在我的代码中使用了这个示例,我想知道是否有任何方法可以使用HttpClient,而不使用async/await
静态异步任务GetProductAsync(字符串路径)
{
Product=null;
HttpResponseMessage response=wait client.GetAsync(路径);
if(响应。IsSuccessStatusCode)
{
product=wait response.Content.ReadAsAsync();
}
退货产品;
}
我在我的代码中使用了这个示例,我想知道是否有任何方法可以使用HttpClient
,而不使用async/await
,以及如何只获得字符串响应
提前感谢您当然您可以:
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))
{
...
}
}
有没有办法在没有async/await的情况下使用HttpClient?我怎样才能只得到响应字符串
HttpClient
是专门为异步使用而设计的
如果要同步下载字符串,请使用
WebClient.DownloadString
仅供参考:这可能会导致ASP.NET和WinForms中出现死锁。在TPL中使用.Result
或.Wait()
时应谨慎。有关死锁的信息,请参阅此部分:为什么不WebClient.DownloadString
而不是扭曲HttpClient
,以避免使用它?哈哈!我刚刚就此发表了评论。答案正确。谢谢,但我只是按照我在question@KumarJ.:遵循指南的一部分是了解需要更改的内容。
using (var client = new WebClient())
{
string response = client.DownloadString(path);
if (!string.IsNullOrEmpty(response))
{
...
}
}