设为首页
加入收藏
站内地图
旧版入口
当前位置:首页 > 站长学院 > 网络编程 > ASP.NET

ASP.NET 2.0 中的异步页功能应用 2

作者:佚名 出处:网络转载 时间:11-10 点击:

内容载入中...
     异步数据绑定
  
    通常情况下,ASP.net 页并不使用 HttpWebRequest 直接请求其他页,但它们通常查询数据库并对结果进行数据绑定。因此,您将如何使用异步页执行异步数据绑定呢?图 4 中的代码隐藏类显示进行此操作的一种方式。
  
  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();
   }
  }
  
  
  
    AsyncDataBind.ASPx.cs 与 AsyncPage.ASPx.cs 使用相同的 AddOnPreRenderCompleteAsync 模式。但是,AsyncDataBind.ASPx.cs 的 BeginAsyncOperation 方法调用 ADO.NET 2.0 中的新方法 SqlCommand.BeginExecuteReader(而非 HttpWebRequest.BeginGetResponse),以执行一个异步数据库查询。当调用完成时,EndAsyncOperation 调用 SqlCommand.EndExecuteReader 以获取 SqlDataReader,然后将其存储在私有字段中。在用于 PreRenderComplete 事件(在异步操作完成但呈现该页之前引发)的事件处理程序中,AsyncDataBind.ASPx.cs 之后将 SqlDataReader 绑定到 Output GridView 控件。从外观上看,该页类似于使用 GridView 呈现数据库查询结果的普通(同步)页。但是在内部,该页更具可伸缩性,因为它并不挂起线程池线程以等待查询返回。
  
  
  
  
  
    。

收藏本文:
】【打印页面】【推荐给朋友】【关闭窗口

站长学院

推荐信息