[英]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欢迎您的评论
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.