ASP.NET WebForm中用async/await实现异步

时间:2022-02-06 04:47:44

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

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

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

ASP.NET WebForm中用async/await实现异步
private async Task GetMyPosts()
{
var posts = await ServiceFactory.BlogPostSevice.GetBlogPostsPagedAsync();
rpPosts.DataSource = posts;
rpPosts.DataBind();
}
ASP.NET WebForm中用async/await实现异步

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

from : http://www.cnblogs.com/dudu/p/aspnet-webform-async.html

不要在 ASP.NET 4.5 Beta 的 Page 类事件上直接使用 async 与 await

下面代码中的这种用法是错误的:

1
2
3
4
5
6
7
8
protected async void Page_Load(object sender, EventArgs e)
{
    WebClient client = new WebClient();
    var result1 = await client.DownloadStringTaskAsync("http://www.website.com");
    WebClient client2 = new WebClient();
    var result2 = await client.DownloadStringTaskAsync(result1);
    //do more
}

在事件上直接使用 async 引发的错误

目前正确的写法
首先,建议把 UseTaskFriendlySynchronizationContext 设置为 true。 另外,正确的写法如下: public partial class WebForm1 : System.Web.UI.Page
{
protected string Msg { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
RegisterAsyncTask(new PageAsyncTask(Method1)); }
private async Task Method1()
{
using (WebService service = new WebService())
{
Msg = await service.HelloWorldTaskSync();
}
} protected void Button_Test_Click(object sender, EventArgs e)
{
RegisterAsyncTask(new PageAsyncTask(Method2));
} private async Task Method2()
{
using (WebService service = new WebService())
{
Msg = await service.HelloWorldTaskSync();
}
}
}
如果需要写异步,一定要用 RegisterAsyncTask 方法,实测证明,支持多次调用,而且会按次序执行。

from:http://www.cnblogs.com/dozer/archive/2012/03/14/async-and-await-in-asp-net-beta.html

参考资料:

http://*.com/questions/9562836/whats-the-meaning-of-usetaskfriendlysynchronizationcontext

http://social.msdn.microsoft.com/Forums/en-NZ/async/thread/b2e8c51e-2808-46d0-92e9-b825321d0af8