MSDN官方的ASP.Net异步页面的经典示例代码
示例1.演示异步获取一个网址的内容,处理后显示在OutPut这一Label上
1using System;
2using System.Web;
3using System.Web.UI;
4using System.Web.UI.WebControls;
5using System.Net;
6using System.IO;
7using System.Text;
8using System.Text.RegularExpressions;
9
10public partial class AsyncPage : System.Web.UI.Page
11{
12 private WebRequest _request;
13
14 void Page_Load (object sender, EventArgs e)
15 {
16 AddOnPreRenderCompleteAsync (
17 new BeginEventHandler(BeginAsyncOperation),
18 new EndEventHandler (EndAsyncOperation)
19 );
20 }
21
22 IAsyncResult BeginAsyncOperation (object sender, EventArgs e,
23 AsyncCallback cb, object state)
24 {
25 _request = WebRequest.Create("http://msdn.microsoft.com");
26 return _request.BeginGetResponse (cb, state);
27 }
28 void EndAsyncOperation (IAsyncResult ar)
29 {
30 string text;
31 using (WebResponse response = _request.EndGetResponse(ar))
32 {
33 using (StreamReader reader =
34 new StreamReader(response.GetResponseStream()))
35 {
36 text = reader.ReadToEnd();
37 }
38 }
39
40 Regex regex = new Regex ("href\\s*=\\s*\"([^\"]*)\"",
41 RegexOptions.IgnoreCase);
42 MatchCollection matches = regex.Matches(text);
43
44 StringBuilder builder = new StringBuilder(1024);
45 foreach (Match match in matches)
46 {
47 builder.Append (match.Groups[1]);
48 builder.Append("<br/>");
49 }
50
51 Output.Text = builder.ToString ();
52 }
53}
54
55
2using System.Web;
3using System.Web.UI;
4using System.Web.UI.WebControls;
5using System.Net;
6using System.IO;
7using System.Text;
8using System.Text.RegularExpressions;
9
10public partial class AsyncPage : System.Web.UI.Page
11{
12 private WebRequest _request;
13
14 void Page_Load (object sender, EventArgs e)
15 {
16 AddOnPreRenderCompleteAsync (
17 new BeginEventHandler(BeginAsyncOperation),
18 new EndEventHandler (EndAsyncOperation)
19 );
20 }
21
22 IAsyncResult BeginAsyncOperation (object sender, EventArgs e,
23 AsyncCallback cb, object state)
24 {
25 _request = WebRequest.Create("http://msdn.microsoft.com");
26 return _request.BeginGetResponse (cb, state);
27 }
28 void EndAsyncOperation (IAsyncResult ar)
29 {
30 string text;
31 using (WebResponse response = _request.EndGetResponse(ar))
32 {
33 using (StreamReader reader =
34 new StreamReader(response.GetResponseStream()))
35 {
36 text = reader.ReadToEnd();
37 }
38 }
39
40 Regex regex = new Regex ("href\\s*=\\s*\"([^\"]*)\"",
41 RegexOptions.IgnoreCase);
42 MatchCollection matches = regex.Matches(text);
43
44 StringBuilder builder = new StringBuilder(1024);
45 foreach (Match match in matches)
46 {
47 builder.Append (match.Groups[1]);
48 builder.Append("<br/>");
49 }
50
51 Output.Text = builder.ToString ();
52 }
53}
54
55
示例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();
}
}
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();
}
}
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();
}
}
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";
}
}
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";
}
}
作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。