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

本文介绍如何在ASP.NET WebForms中实现页面异步加载,通过具体示例展示了如何使用`PageAsyncTask`进行异步操作,如抓取URL内容并将其保存到文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘要

最近想着将项目中的部分耗时的操作,进行异步化。就自己弄个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.youkuaiyun.com/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

转载于:https://www.cnblogs.com/wolf-sun/p/5620265.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值