asp.net webform中使用async,await实现异步操作
2016-06-27 15:17
1271 查看
摘要
最近想着将项目中的部分耗时的操作,进行异步化。就自己弄个demo进行学习。只需下面几个步骤就可以将aspx页面中注册异步操作。demo
比如我们需要抓取某个url的内容,这个时候我们可能会有下面的一个方法。using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Wolfy.AsyncWeb { public partial class Index : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.Page.RegisterAsyncTask(new PageAsyncTask(GetHtmlAsync)); } } private async Task GetHtmlAsync() { string url = "http://www.cnblogs.com/"; WebClient client = new WebClient(); client.Encoding = Encoding.UTF8; string html = await client.DownloadStringTaskAsync(url); string strPath = MapPath("~/html"); if (!Directory.Exists(strPath)) { Directory.CreateDirectory(strPath); } string savePath = Path.Combine(strPath, "blog.txt"); using (FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { byte[] buffer = Encoding.UTF8.GetBytes(html); await fs.WriteAsync(buffer, 0, buffer.Length); } } } }
这时候以为大功告成了,浏览页面的时候发现还是少了点东西。
找到对应的页面添加上async特性。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Wolfy.AsyncWeb.Index" Async="true" %>
结果
参考
http://blog.csdn.net/youaregoo/article/details/8973387
http://mrbool.com/how-to-create-asynchronous-device-page-in-asp-net-4-5/26022
http://www.cnblogs.com/dudu/p/aspnet-webform-async.html
相关文章推荐
- ASP.NET MVC 实现二级域名
- asp.net form 验证方式的使用(转载)
- asp.net下通过泛解析和伪静态实现二级域名的实现方法
- ASP.NET MVC AJAX的调用示例
- ASP.NET Session 详解
- WebForm页面生命周期及asp.net运行机制
- .NET/ASP.NET Routing路由(深入解析路由系统架构原理)
- ASP 连接Access2013的accdb文件
- spring AspectJ的Execution表达式-备忘札记
- JDK8:PermGen变更为MetaSpace详解
- ASPNET常用工具方法(二)
- 利用ASP.NET MVC+Bootstrap搭建个人博客之打造清新分页Helper(三)
- [转]asp.net c# 网上搜集面试题目(附答案)
- 利用ASP.NET MVC+Bootstrap搭建个人博客之praise.js点赞特效插件(二)
- aspnet常用工具方法(一)
- 利用ASP.NET MVC和Bootstrap快速搭建响应式个人博客站(一)
- ASPNET的网站静态化URL重写
- ASP.Net 对xml文件的读写,添加,修改,删除操作
- ASP.Net中,如何自动保存文件到指定位置
- 利用Aspose.Word控件和Aspose.Cell控件,实现Word文档和Excel文档的模板化导出