我正在尝试使用“async”和“await”提供的功能来异步下载网页内容,但我遇到了任务永远等待完成的问题。您能否让我知道以下代码片段有什么问题?
protected void Page_Load(object sender, EventArgs e)
{
var websites = new string[] {"http://www.cnn.com","http://www.foxnews.com"};
var tasks = websites.Select(GenerateSomeContent).ToList();
//I don't want to use 'await Tasks.WhenAll(tasks)' as I need to block the
//page load until the all the webpage contents are downloaded
Task.WhenAll(tasks).Wait();
//This line is never hit on debugging
var somevalue = "Complete";
}
static async Task<Results> GenerateSomeContent(string url)
{
var client = new HttpClient();
var response = await client.GetAsync(url); //Await for response
var content = await response.Content.ReadAsStringAsync();
var output = new Results {Content = content};
return output;
}
//Sample class to hold results
public class Results
{
public string Content;
}