C#异步任务无限期等待

我正在尝试使用“异步”和“ “等待”异步下载网页内容,我遇到了任务正在等待永远完成的问题.你能让我知道以下代码片段有什么问题吗?

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;
}
最佳答案
首先,确保您运行在.NET 4.5,而不是.NET 4.0. ASP.NET在.NET 4.5中被异步化.

那么正确的解决方案是等待Task.WhenAll的结果:

var tasks = websites.Select(GenerateSomeContent);
await Task.WhenAll(tasks);

ASP.NET管道(仅在.NET 4.5中)将检测到您的代码正在等待,并将停止该请求,直到Page_Load运行完成为止.

在这种情况下使用Wait来同步阻止任务会导致死锁as I explain on my blog.

转载注明原文:C#异步任务无限期等待 - 代码日志