C# async tasks waiting indefinitely

大城市里の小女人 提交于 2019-12-04 02:11:10
Stephen Cleary

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.

+1 Stephen Cleary. Just came to know you need to have async before void type with Page_Load as given below:

protected async void Page_Load(object sender, EventArgs e)
{
   var tasks = websites.Select(GenerateSomeContent);
   await Task.WhenAll(tasks);
}

And then in your code-behind file (in case asp.net web form app) should also have Async="true" attribute.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Async="true" Inherits="EmptyWebForm._default" %>

Hope this helps visitors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!