且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不异步的情况下使用HttpClient

更新时间:2022-06-08 22:22:08

您当然可以:

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所说:

but as @MarcinJuraszek said:

这可能会导致ASP.NET和WinForms中的死锁.使用.Result或带有TPL的.Wait()应该格外小心".

"That may cause deadlocks in ASP.NET and WinForms. Using .Result or .Wait() with TPL should be done with caution".

以下是 WebClient.DownloadString

using (var client = new WebClient())
{
    string response = client.DownloadString(path);
    if (!string.IsNullOrEmpty(response))
    {
       ...
    }
}