MSDN官方的ASP.Net异步页面的经典示例代码

示例1.演示异步获取一个网址的内容,处理后显示在OutPut这一Label上

using System;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Net;

using System.IO;

using System.Text;

using System.Text.RegularExpressions;



public partial class AsyncPage : System.Web.UI.Page

{

    private WebRequest _request;



    void Page_Load (object sender, EventArgs e)

    {

        AddOnPreRenderCompleteAsync (

            new BeginEventHandler(BeginAsyncOperation),

            new EndEventHandler (EndAsyncOperation)

        );

    }



    IAsyncResult BeginAsyncOperation (object sender, EventArgs e, 

        AsyncCallback cb, object state)

    {

        _request = WebRequest.Create("http://msdn.microsoft.com");

        return _request.BeginGetResponse (cb, state);

    }

    void EndAsyncOperation (IAsyncResult ar)

    {

        string text;

        using (WebResponse response = _request.EndGetResponse(ar))

        {

            using (StreamReader reader = 

                new StreamReader(response.GetResponseStream()))

            {

                text = reader.ReadToEnd();

            }

        }



        Regex regex = new Regex ("href\\s*=\\s*\"([^\"]*)\"", 

            RegexOptions.IgnoreCase);

        MatchCollection matches = regex.Matches(text);



        StringBuilder builder = new StringBuilder(1024);

        foreach (Match match in matches)

        {

            builder.Append (match.Groups[1]);

            builder.Append("<br/>");

        }



        Output.Text = builder.ToString ();

    }

}

示例2:演示如何异步从数据库查询数据,并将返回的DataReader绑定到指定控件上

using System;

using System.Data;

using System.Data.SqlClient;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Configuration;



public partial class AsyncDataBind : System.Web.UI.Page

{

    private SqlConnection _connection;

    private SqlCommand _command;

    private SqlDataReader _reader;





    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            // Hook PreRenderComplete event for data binding

            this.PreRenderComplete += 

                new EventHandler(Page_PreRenderComplete);



            // Register async methods

            AddOnPreRenderCompleteAsync(

                new BeginEventHandler(BeginAsyncOperation),

                new EndEventHandler(EndAsyncOperation)

            );

        }

    }

    IAsyncResult BeginAsyncOperation (object sender, EventArgs e, 

        AsyncCallback cb, object state)

    {

        string connect = WebConfigurationManager.ConnectionStrings

            ["PubsConnectionString"].ConnectionString;

        _connection = new SqlConnection(connect);

        _connection.Open();

        _command = new SqlCommand(

            "SELECT title_id, title, price FROM titles", _connection);

        return _command.BeginExecuteReader (cb, state);

    }



    void EndAsyncOperation(IAsyncResult ar)

    {

        _reader = _command.EndExecuteReader(ar);

    }



    protected void Page_PreRenderComplete(object sender, EventArgs e)

    {

        Output.DataSource = _reader;

        Output.DataBind();

    }



    public override void Dispose()

    {

        if (_connection != null) _connection.Close();

        base.Dispose();

    }

}

示例3:异步调用WebService

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;



public partial class AsyncWSInvoke1 : System.Web.UI.Page

{

    private WS.PubsWebService _ws;

    private DataSet _ds;



    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            // Hook PreRenderComplete event for data binding

            this.PreRenderComplete += 

                new EventHandler(Page_PreRenderComplete);



            // Register async methods

            AddOnPreRenderCompleteAsync(

                new BeginEventHandler(BeginAsyncOperation),

                new EndEventHandler(EndAsyncOperation)

            );

        }

    }



    IAsyncResult BeginAsyncOperation (object sender, EventArgs e, 

        AsyncCallback cb, object state)

    {

        _ws = new WS.PubsWebService();

        // Fix up URL for call to local VWD-hosted Web service

        _ws.Url = new Uri(Request.Url, "Pubs.asmx").ToString();

        _ws.UseDefaultCredentials = true;

        return _ws.BeginGetTitles (cb, state);

    }



    void EndAsyncOperation(IAsyncResult ar)

    {

        _ds = _ws.EndGetTitles(ar);

    }



    protected void Page_PreRenderComplete(object sender, EventArgs e)

    {

        Output.DataSource = _ds;

        Output.DataBind();

    }



    public override void Dispose()

    {

        if (_ws != null) _ws.Dispose();

        base.Dispose();

    }

}

示例4:还是异步调用WebService,但换了一种方法

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;



public partial class AsyncWSInvoke2 : System.Web.UI.Page

{

    private WS.PubsWebService _ws;

    private DataSet _ds;



    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            // Hook PreRenderComplete event for data binding

            this.PreRenderComplete += 

                new EventHandler(Page_PreRenderComplete);



            // Call the Web service asynchronously

            _ws = new WS.PubsWebService();

            _ws.GetTitlesCompleted += new 

                WS.GetTitlesCompletedEventHandler(GetTitlesCompleted);

            _ws.Url = new Uri(Request.Url, "Pubs.asmx").ToString();

            _ws.UseDefaultCredentials = true;

            _ws.GetTitlesAsync();

        }

    }



    void GetTitlesCompleted(Object source, 

        WS.GetTitlesCompletedEventArgs e)

    {

        _ds = e.Result;

    }



    protected void Page_PreRenderComplete(object sender, EventArgs e)

    {

        Output.DataSource = _ds;

        Output.DataBind();

    }



    public override void Dispose()

    {

        if (_ws != null) _ws.Dispose();

        base.Dispose();

    }

}

示例5:跟示例1差不多,但是加了TimeOut处理

using System;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Net;

using System.IO;

using System.Text;

using System.Text.RegularExpressions;



public partial class AsyncPageTask : System.Web.UI.Page

{

    private WebRequest _request;



    protected void Page_Load(object sender, EventArgs e)

    {

        PageAsyncTask task = new PageAsyncTask(

            new BeginEventHandler(BeginAsyncOperation),

            new EndEventHandler(EndAsyncOperation),

            new EndEventHandler(TimeoutAsyncOperation),

            null

        );

        RegisterAsyncTask(task);

    }



    IAsyncResult BeginAsyncOperation(object sender, EventArgs e, 

        AsyncCallback cb, object state)

    {

        _request = WebRequest.Create("http://msdn.microsoft.com");

        return _request.BeginGetResponse(cb, state);

    }



    void EndAsyncOperation(IAsyncResult ar)

    {

        string text;

        using (WebResponse response = _request.EndGetResponse(ar))

        {

            using (StreamReader reader = 

                new StreamReader(response.GetResponseStream()))

            {

                text = reader.ReadToEnd();

            }

        }



        Regex regex = new Regex("href\\s*=\\s*\"([^\"]*)\"", 

            RegexOptions.IgnoreCase);

        MatchCollection matches = regex.Matches(text);



        StringBuilder builder = new StringBuilder(1024);

        foreach (Match match in matches)

        {

            builder.Append(match.Groups[1]);

            builder.Append("<br/>");

        }



        Output.Text = builder.ToString();

    }



    void TimeoutAsyncOperation(IAsyncResult ar)

    {

        Output.Text = "Data temporarily unavailable";

    }

}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏跟着阿笨一起玩NET

linq to sql 扩展方法

9000
来自专栏跟着阿笨一起玩NET

C#操作Url参数

31010
来自专栏王磊的博客

Net连接mysql的公共Helper类MySqlHelper.cs带MySql.Data.dll下载

MySqlHelper.cs代码如下: using System; using System.Collections.Generic; using System...

56890
来自专栏james大数据架构

Excel导入导出数据库01

主要分为两部份 1.Excel操作类 1 引入 2 using System.Data.OleDb; 3 using System.IO; 4 ...

258100
来自专栏阿炬.NET

【要什么自行车】ASP.NET MVC4笔记03:调用编辑器 kindeditor

32250
来自专栏大内老A

开发自己的Data Access Application Block[下篇]

上接:[原创] 我的ORM: 开发自己的Data Access Application Block - Part I 4. Database 下面来介绍重中之重...

24460
来自专栏一个爱瞎折腾的程序猿

使用HttpDownLoadHelper下载文件

13710
来自专栏王磊的博客

HttpWebRequest采集读取网站挂载Cookie的通用方法

Asp.net 版本 HttpWebRequest采集时添加:httpWebRequest.CookieContainer = new CookieContai...

31850
来自专栏跟着阿笨一起玩NET

C#自定义泛型类绑定ComboBox控件

C# WinForm ComboBox 自定义数据项 (ComboBoxItem )

26010
来自专栏大内老A

以上下文(Context)的形式创建一个共享数据的容器

在很多情况下我们具有这样的需求:为一组相关的操作创建一个执行上下文并提供一个共享的数据容器,而不是简单地定义一个全局变量,或者将数据通过参数传来传去。这样的上下...

21350

扫码关注云+社区

领取腾讯云代金券