asp.net webform中使用async,await实现异步操作

Posted jeely

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了asp.net webform中使用async,await实现异步操作相关的知识,希望对你有一定的参考价值。

摘要

最近想着将项目中的部分耗时的操作,进行异步化。就自己弄个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 webform中使用async,await实现异步操作的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET WebForm的优缺点

Asp.net中WebForm 与 MVC的架构区别

ASP.NET WebForm / MVC 源码分析

Asp.net: WebForm基础上构建Mvc的方法

ASP.NET WebForm中有多线程的概念吗?

想要从 XElements 中提取标签并在 ASP.NET Webform 上显示为网格