How to use async/await to achieve asynchronous page in asp.net webform?(如何在asp.net webform中使用async/await实现异步页面?)
问题描述
我们现在可以在 ASP.NET MVC 4 中使用 async/await 关键字.
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?
推荐答案
一种简单的方法是让您的事件处理程序 async.首先,将 Async="true" 参数添加到 @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不起作用(请参阅此 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.此外,他们添加了检查您是否不正确地使用 async 事件处理程序.观看此视频了解详情.
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 webform中使用async/await实现异步页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在asp.net webform中使用async/await实现异步页面
基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
