例子1:在当前页面获取另一个页面的内容:
aspx:
<%@ Page Async="true"...><asp:Label ID="lbOutPut" runat="server"></asp:Label>
aspx.cs:
Code
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
private WebRequest _request;
protected void Page_Load(object sender, EventArgs e)
{
//为异步页注册开始和结束事件处理程序委托
AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation));
}
IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object state) //BeginEventHandler
{
_request = WebRequest.Create("http://www.cnblogs.com");
return _request.BeginGetResponse(cb, state); //获取响应开始
}
void EndAsyncOperation(IAsyncResult ar) //EndEventHandler
{
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/>");
}
lbOutPut.Text = builder.ToString();
} 异步任务(修改上述的部分代码如下):
Code
protected void Page_Load(object sender, EventArgs e)
{
PageAsyncTask task = new PageAsyncTask(
new BeginEventHandler(BeginAsyncOperation),
new EndEventHandler(EndAsyncOperation),
new EndEventHandler(TimeoutAsyncOperation), //超时操作
null);
RegisterAsyncTask(task);
}
//增加函数
void TimeoutAsyncOperation(IAsyncResult ar)
{
lbOutPut.Text = "Data temporarily unavailable";
} 例子2:异步数据绑定
aspx:
<%@ Page Async="true"...><asp:GridView ID="MyGirdView" runat="server"...>...</asp:GridView>
aspx.cs:
Code
using System.Web.Configuration;
using System.Data.Sql;
using System.Data.SqlClient;
private SqlConnection _conn;
private SqlCommand _cmd;
private SqlDataReader _sdr;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.PreRenderComplete += new EventHandler(Page_PreRenderComplete); //override OnPreRenderComplete
AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation));
}
}
IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object state)
{
string ConnStr = WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString; //System.Web.Configuration;
//web.config <connectionStrings><add name="Conn" connectionString=";async=true"/>
_conn = new SqlConnection(ConnStr);
_conn.Open();
_cmd = new SqlCommand("Select TableId,TableData From TableName", _conn);
return _cmd.BeginExecuteReader(cb, state);
}
void EndAsyncOperation(IAsyncResult ar) //EndEventHandler
{
_sdr = _cmd.EndExecuteReader(ar);
}
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
MyGridView.DataSource = _sdr;
MyGridView.DataBind();
}
public override void Dispose()
{
if (_conn != null) _conn.Close();
base.Dispose();
} 例子3:异步调用WebService
aspx:
<%@ Page Async="true"...>
aspx.cs:
Code
private localhost.Service _ws;
private DataSet _ds;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.PreRenderComplete += new EventHandler(Page_PreRenderComplete); //override OnPreRenderComplete
AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation));
}
}
IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object state)
{
_ws = new localhost.Service();
_ws.Url = new Uri(Request.Url, "Service.asmx").ToString();
_ws.UseDefaultCredentials = true; //使用当前线程的帐号密码进行后端资源的访问
return _ws.BeginGetTableInfo(cb, state);
}
void EndAsyncOperation(IAsyncResult ar)
{
_ds = _ws.EndGetTableInfo(ar);
}
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
MyGridView.DataSource = _ds;
MyGridView.DataBind();
}
public override void Dispose()
{
if (_ws != null) _ws.Dispose();
base.Dispose();
} WebServie(WS/App_Code/Serviec.cs):
Code
[WebMethod]
public DataSet GetTableInfo()
{
string ConnStr = WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
SqlDataAdapter sda = new SqlDataAdapter("Select TableId,TableData From TableName", ConnStr);
DataSet ds = new DataSet();
sda.Fill(ds);
return ds;
} ajax技术和异步页面技术的区别:
1。实现方式不同(ajax是用js在客户端实现,异步页面技术是在服务器端实现),即代码运行位置不同。
2。适用情况不同:
异步页面技术是为了服务器端的性能提升,比如IO操作,外部服务操作(HttpRequest,WebService),大数据量(数据库)操作时,可以提高吞吐量(可以让系统的工作线程可以尽快回到线程池中去,缩短线程的工作周期)。应用于请求很多,每个请求处理的周期很长的情况。
ajax是为了解决客户端到服务器端的数据往返问题(受网络带宽影响),所有的处理都在客户端进行(不占用服务端资源)避免网络传输带来的瓶颈。