我一直试图通过WebClient api阅读页面。但页面太大,响应太慢。有时我需要等待2分半钟才能得到完整的回复。
var client = new WebClient();
var stream = client.OpenRead("http://example.com");
using (var sr = new StreamReader(stream))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// add line and do something else
}
}
必须有更好的方法来处理它。我可以异步检索这些数据并在回调中完成我的工作吗?
答案 0 :(得分:1)
这是使用HttpClient的示例。此方法将需要返回任务或任务<>并标记为异步。
using (var httpClient = new HttpClient())
{
// This will process async
var results = await httpClient.GetAsync("http://example.com");
// This will process async
var stream = await results.Content.ReadAsStreamAsync();
using (var sr = new StreamReader(stream))
{
string line;
while ((line = await sr.ReadLineAsync()) != null)
{
// add line and do something else
}
}
}