且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#异步任务无限期等待

更新时间:2023-01-23 18:29:02

首先,确保你在.NET 4.5上运行,而不是.NET 4.0。 ASP.NET被做了异步 -Aware在.NET 4.5。

然后,适当的解决办法就是等待的结果 Task.WhenAll

  VAR任务= websites.Select(GenerateSomeContent);
等待Task.WhenAll(任务);

ASP.NET管道(在.NET 4.5只),将检测到您的code是等待和荷兰国际集团将停止,直到的Page_Load 运行结束。

同步方式使用等待在这种情况下导致死锁的我在我的博客解释。

I am trying to use the functionality provided by "async" & "await" to asynchronously download webpage content and I have into issues where the Tasks are waiting forever to complete. Could you please let me know what is wrong with the following code snippet?

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;
}

First, make sure you're running on .NET 4.5, not .NET 4.0. ASP.NET was made async-aware in .NET 4.5.

Then, the proper solution is to await the result of Task.WhenAll:

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

The ASP.NET pipeline (in .NET 4.5 only) will detect that your code is awaiting and will stall that request until Page_Load runs to completion.

Synchronously blocking on a task using Wait in this situation causes a deadlock as I explain on my blog.