亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

asp.net webform中使用

標簽:
JavaScript

摘要

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

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消