如何使用异步/等待在asp.net网络表单来实现异步页? [英] How to use async/await to achieve asynchronous page in asp.net webform?

查看:159
本文介绍了如何使用异步/等待在asp.net网络表单来实现异步页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们现在可以使用异步/的await关键词在ASP.NET MVC 4。

We can now use the async/await key words in ASP.NET MVC 4.

public async Task<ActionResult> TestAsync()
{
    WebClient client = new WebClient();
    return Content(await client.DownloadStringTaskAsync("http://www.google.com"));
}

但如何使用它在ASP.NET的WebForms?

But how to use it in ASP.NET WebForms?

推荐答案

一个简单的方法是只让你的事件处理程序异步。首先,添加异步=真正的参数设置为 @Page 指令,然后你应该能够编写异步事件处理这样:

One easy way is to just make your event handlers async. First, add the Async="true" parameter to the @Page directive, and then you should be able to write async event handlers as such:

protected async void Page_Load(object sender, EventArgs e)
{
  var client = new WebClient();
  var content = await client.DownloadStringTaskAsync("http://www.google.com");
  Response.Write(content);
}

我说:应该能,因为我还没有真正尝试这一点我自己。但它应该工作。

I say "should be able to" because I haven't actually tried this out myself. But it should work.

更新:这确实的的为的Page_Load 工作(见<一href=\"http://social.msdn.microsoft.com/Forums/en-US/async/thread/b2e8c51e-2808-46d0-92e9-b825321d0af8\">this MSDN论坛主题),而应适用于其他的事件,如按钮点击。

Update: This does not work for Page_Load (see this MSDN forum thread), but should work for other events such as button clicks.

更新:此的确实的在ASP.NET 4.5 的Page_Load 的工作。此外,他们增加了检查,如果不正确使用异步事件处理程序。 详见这部影片。

Update: This does work for Page_Load in ASP.NET 4.5. Also, they added checks if you improperly use an async event handler. See this video for details.

这篇关于如何使用异步/等待在asp.net网络表单来实现异步页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆