ASP.NET WebForm中用async/await实现异步出人意料的简单

时间:2024-11-25 11:07:43

1. 在.aspx中添加异步标记

<%@ Page Language="C#" Async="true"%>

2. 在.aspx.cs或者.ascx.cs(用户控件)中添加异步方法

private async Task GetMyPosts()
{
var posts = await ServiceFactory.BlogPostSevice.GetBlogPostsPagedAsync();
rpPosts.DataSource = posts;
rpPosts.DataBind();
}

3. 在.aspx.cs或者.ascx.cs的Page_Load或者OnLoad注册异步方法

protected void Page_Load(object sender, EventArgs e)
{
this.Page.RegisterAsyncTask(new PageAsyncTask(GetMyPosts));
}

搞定!

【参考资料】

How to create Asynchronous device Page in ASP.NET 4.5