C#异步任务无限期等待 [英] C# async tasks waiting indefinitely
问题描述
我试图使用由异步&放大器提供的功能; 等待异步下载网页内容,我必须到那里的任务在等待永远完成的问题。能否请你让我知道什么是错用下面的code段?
保护无效的Page_Load(对象发件人,EventArgs的发送)
{
VAR网站=新的String [] {http://www.cnn.com,http://www.foxnews.com};
变种任务= websites.Select(GenerateSomeContent).ToList(); //我不想用'等待Tasks.WhenAll(任务)因为我需要阻止
//页面加载,直到所有的网页内容下载
Task.WhenAll(任务).Wait(); //此行是从来没有打在调试
VAR someValue中=完成;
}静态异步任务<结果> GenerateSomeContent(字符串URL)
{
VAR的客户=新的HttpClient();
VAR响应=等待client.GetAsync(URL); //指日可待响应
VAR内容=等待response.Content.ReadAsStringAsync();
无功输出=新的结果{内容=内容};
返回输出;
}// Sample类来保存结果
公共类结果
{
公共字符串的内容;
}
首先,确保你在.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 await
ing 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.
这篇关于C#异步任务无限期等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!