简体   繁体   English

调用 HttpClient GetAsync 但应用程序冻结秒并作为同步模式工作

[英]call HttpClient GetAsync but app freezes seconds and works as sync mode

Below is my code to get an HTML page下面是我获取 HTML 页面的代码

  public static async Task<string> GetUrltoHtml(string url)

    {
        string s;
        using (var client = new HttpClient())
        {

            var result = client.GetAsync(url).Result;
            //Console.WriteLine("!!!"+result.StatusCode);
            s = result.Content.ReadAsStringAsync().Result; //break point


        }
        return s;
    }

the line线

var result = client.GetAsync(url).Result;

causes app freeze seconds and work as sync mode导致应用程序冻结秒并作为同步模式工作

Your comment welcome欢迎您的评论

According to the docs根据文档

Accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete;访问属性的 get 访问器会阻塞调用线程,直到异步操作完成; it is equivalent to calling the Wait method.相当于调用Wait方法。

So getting Result is a blocking action.所以获取Result是一个阻塞动作。 You should use await instead.您应该改用await

s = await result.Content.ReadAsStringAsync();

( Result is helpful when the result is ready and you just want to get it. Or in some cases you want to block the thread (but it's not recommended).) (当结果准备好并且您只想获取它时, Result很有用。或者在某些情况下您想阻塞线程(但不推荐)。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HttpClient GetAsync 冻结 - HttpClient GetAsync freezes HttpClient GetAsync 耗时约 2 秒 - HttpClient GetAsync taking ~2 seconds HttpClient getAsync 只工作一次 - HttpClient getAsync just works once HttpClient调用保持等待模式,但在Console App中运行良好 - HttpClient call keeps on waiting mode but works fine in Console App HttpClient.GetAsync在一个类中起作用,但在另一个类中不起作用 - HttpClient.GetAsync works in one class but not in the other 使用 C# HttpClient API 和邮递员测试之间的区别? 客户端调用适用于邮递员,但不适用于 C# httpClient getAsync - Differences between using C# HttpClient API and the postman testing? Client call works on postman, but not C# httpClient getAsync 在控制台应用程序中调用HttpClient.GetAsync-死锁 - Call HttpClient.GetAsync in console application - Deadlock 为什么在我的 C# asp 表单应用程序中第一个 HttpClient.GetAsync 调用非常慢? - Why is first HttpClient.GetAsync call extremely slow in my C# asp form app? HttpClient.GetAsync(url)将504返回到在浏览器中工作的URL - HttpClient.GetAsync(url) returns 504 to a URL which works in the browser 使用HttpClient.GetAsync来调用Web API似乎挂了 - Using HttpClient.GetAsync to call Web API seems to hang
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM