体验ASP.NET 2.0中的异步页面功能
墨初 知识笔记 79阅读
在网上输入ASP.NET 2.0中的异步页面功能就能找到相关信息,基本操作他也讲得很好。你可以上去看看。但是在这篇文章的最后,我写了(3)。遗留问题。第二种方式,数据库对象SqlCommand实现异步调用函数(对应示例代码中的:页AsyncVisitDatabase.aspx)。我从来没有调试成功过样本代码!数据库中有数据,但无法在GridView中显示。那我就在这里补上。privateWebRequest _ requestprivateSqlConnection _ connection;privateSqlCommand _ commandprivateSqlDataReader _ readerDataTabletable=new datatable();protectedvoidPage _ Load(object sender,EventArgse){//
le="color: rgba(0, 128, 0, 1)"> //注册异步调用的Begin和End方法.if (!IsPostBack)
{
//注册事件Page_PreRender执行完成时执行方法(其实这一个是不用写的,当你调试的时候你会发现Page_PreRenderComplete会运行了两次,因为页面打开时就已经应该运行了)
//this.PreRenderComplete += new EventHandler(Page_PreRenderComplete);
/**/
///注册异步调用的Begin和End方法.
AddOnPreRenderCompleteAsync(
new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation));
}
}
//异步调用开始方法(当执行此方法时,当前线程就回到线程池,等待为其它请求服务).
IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object state)
{
//_request = WebRequest.Create("");
//return _request.BeginGetResponse(cb, state);
string connect = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
_connection = new SqlConnection(connect);
_connection.Open();
_command = new SqlCommand("select * from gsjbxx", _connection);
return _command.BeginExecuteReader(cb, state);
}
//异步调用结束后的接收方法(异步操作执行完成后,会重新从线程池中取个线程为本页面请求服务).
void EndAsyncOperation(IAsyncResult ar)
{
_reader = _command.EndExecuteReader(ar);
//为了确保我得到了相应的数据并可以显示在DATAVIEW中
table.Load(_reader);
}
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
this.GridView1.DataSource = table;
this.GridView1.DataBind();
}
大家也可以看看这里的介绍, PageAsyncTask 的方式则是增强版本,除了异步页面处理开始和结束方法自身外,还可以提供在超时情况下的处理方法,以及处理时的状态对象,这一个就更好地处理了异步页面

最后提一提,不知道是不是个人电脑问题,在运行异步页面与不使用异步页面时,查看CPU的占用是异步页面的要比不使用异步的要底,这就可以证明使用异步可以减少服务器的负荷。

标签: