References:
ASP.NET 2.0 中的异步页
http://www.microsoft.com/china/msdn/library/webservices/asp.net/issuesWickedCodetoc.mspx?mfr=trueIntroduction:
在asp.net2.0提供了异步页的支持。具体参考上文。这里简单叙述一下。
1)页面接受用户请求,使用调用WebRequest获取另外一个网站的信息。
2)当获取完毕,页面再次处理获取结果,返回用户。
3)过程中的获取是异步的,服务器不始终保持和用户的联系,解放了线程池。
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 (); //Output是页面一个Label
}
}
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 (); //Output是页面一个Label
}
}
红色部分是重点。大概流程:
。aspx主线程接受到了用户请求,打开异步模式处理BeginAsyncOperation。
。在方法BeginAsyncOperation里面,执行异步WebRequest.Create,并且返回一个IAsyncResult给主线程。主线程停止,回收到线程池。
。当WebRequest处理完毕后,通过IAsyncResult通知回主线程,主线程再次接管,调用EndAsyncOperation 处理剩下的部分。