Experience the asynchronous page features in ASP.net 2.0

Source: Internet
Author: User
Tags execution implement connect new features thread tostring
Asp.net| asynchronous (i). Simple introduction to the principle of implementation

The following illustration left is a procedure that does not use the asynchronous page feature (ASP.net 1.0), and the following illustration uses the asynchronous page execution process (asp.net 2.0).


(ASP.net 1.0 general processing process) (Asynchronous page feature processing using ASP.NET 2.0 new features)
From the left figure, one thread is always serving the request of the same page throughout the request process.

As can be seen from the right figure, in a page request process, can be different threads for this page request service.

Obviously, the use of the graph in the number of client requests, the overall efficiency of the site is high. Because:

1. When an asynchronous page is not used, a thread can only serve requests for the same page. This thread is still waiting even when the page request processes other I/O operations. When this page finishes using this thread, it is put back to the thread pool. The number of threads is limited! So when the thread is not used in time to put back to the line pool can be greatly improved system performance!

2. When using the asynchronous page feature, as in the right figure, the start Thread1 is for the page, but when the page handles other things (such as I/O or calls to other webservice), Thread1 is put back into the thread pool, at which point Thread1 can request services for other pages. When this page finishes its own operation, Thread2 then requests service for the page, not the original thread Thread1 used. This will improve the scalability of the site.

(b). Examples of Usage methods

I. Implement asynchronous page functionality with Page.addonprerendercompleteasync

A. Page Flag Plus properties: async= "true", add the following code:

<%@ Page language= "C #" autoeventwireup= "true"
Codefile= "AsyncPage.aspx.cs"
inherits= "_default" async= "true"%>
B. Background asynchronous page related code:

1private WebRequest _request;
2 protected void Page_Load (object sender, EventArgs e)
3 {
4//Register the Begin and end methods of an asynchronous call.
5 AddOnPreRenderCompleteAsync (
6 new BeginEventHandler (beginasyncoperation),
7 new EndEventHandler (endasyncoperation)
8);
9}
10
11//Asynchronous Call Start Method (when this method is executed, the current thread is returned to the thread pool, waiting to be serviced for another request).
IAsyncResult Beginasyncoperation (object sender, EventArgs E, AsyncCallback cb, Object State)
13 {
_request = WebRequest.Create ("http://blog.csdn.net/chengking/");
Return _request. BeginGetResponse (CB, State);
16}
17
18//The Receive method after the end of an asynchronous call (after the execution of the asynchronous operation completes, it will again fetch a thread from the thread pool to request service for this page).
void Endasyncoperation (IAsyncResult ar)
20 {
string text;
The using (WebResponse response = _request. EndGetResponse (AR))
23 {
using (StreamReader reader = new StreamReader (response). GetResponseStream ()))
25 {
-Text = reader. ReadToEnd ();
27}
28}
This.lbOupput.Text = Text;
30}
2. The database object SqlCommand implements the asynchronous invocation function.

A. Page Flag Plus properties: async= "true", add the following code:

<%@ Page language= "C #" autoeventwireup= "true"
Codefile= "AsyncPage.aspx.cs"
inherits= "_default" async= "true"%>
B. Background code

1public Partial class AsyncVisitDatabase:System.Web.UI.Page
2{
3//Define Data manipulation objects
4 Private SqlConnection _connection;
5 Private SqlCommand _command;
6 Private SqlDataReader _reader;
7
8 protected void Page_Load (object sender, EventArgs e)
9 {
Ten if (! IsPostBack)
11 {
12//Registration Event Page_PreRender execution method when execution completes
this. Prerendercomplete + = new EventHandler (page_prerendercomplete);
14
15/**////registers the begin and end methods of an asynchronous call.
AddOnPreRenderCompleteAsync (
The new BeginEventHandler (beginasyncoperation),
New EndEventHandler (Endasyncoperation)
19);
20}
21}
22
23//Asynchronous Call Start Method (when this method is executed, the current thread is returned to the thread pool, waiting to be serviced for another request).
IAsyncResult Beginasyncoperation (object sender, EventArgs E, AsyncCallback cb, Object State)
25 {
String connect = webconfigurationmanager.connectionstrings["ConnectionString"]. ConnectionString;
_connection = new SqlConnection (connect);
_connection. Open ();
_command = new SqlCommand ("SELECT * from Sales", _connection);
Return _command. Beginexecutereader (CB, State);
31}
32
33//The Receive method after the end of an asynchronous call (after the execution of the asynchronous operation completes, it will again fetch a thread from the thread pool to request service for this page).
void Endasyncoperation (IAsyncResult ar)
35 {
_reader = _command. Endexecutereader (AR);
37}
38
39//Event Page_PreRender executes the method when execution completes, where an asynchronous call returns results to the controls on the page or to other aftermath operations.
protected void Page_prerendercomplete (object sender, EventArgs e)
41 {
Gridview1.datasource = _reader;
Gridview1.databind ();
44}
45
override void Dispose ()
47 {
if (_connection!= null)
_connection. Close ();
Base. Dispose ();
51}
52}
3. Implement asynchronous Call WebService

A. Page Flag Plus properties: async= "true", add the following code:
 
<%@ Page language= "C #" autoeventwireup= "true"
Codefile= "AsyncPage.aspx.cs"
inherits= "_default" async= "true"%>
B. Background code

WebService method (Generate data).

1public class WebService:System.Web.Services.WebService {
2
3 public WebService () {
4
5//uncomment The following line if using designed components
6//initializecomponent ();
7}
8
9 [WebMethod]
Ten public DataSet GetData () {
One return Createdata ();
12}
13
Private DataSet Createdata ()
15 {
DataTable dttypechild = new DataTable ();
DTTYPECHILD.COLUMNS.ADD (New DataColumn ("typeID", typeof (int));
DTTYPECHILD.COLUMNS.ADD (New DataColumn ("Typedetail", typeof (String));
//add data
DataRow drChild1 = Dttypechild.newrow ();
drchild1["typeID"] = 1;
drchild1["Typedetail"] = "Apple";
DTTYPECHILD.ROWS.ADD (DRCHILD1);
DataRow drChild2 = Dttypechild.newrow ();
drchild2["typeID"] = 2;
drchild2["Typedetail"] = "orange";
DTTYPECHILD.ROWS.ADD (DRCHILD2);
DataRow drChild3 = Dttypechild.newrow ();
drchild3["typeID"] = 3;
drchild3["Typedetail"] = "banana";
DTTYPECHILD.ROWS.ADD (DRCHILD3);
DataRow drChild4 = Dttypechild.newrow ();
drchild4["typeID"] = 4;
drchild4["Typedetail"] = "pineapple";
DTTYPECHILD.ROWS.ADD (DRCHILD4);
DataRow drChild5 = Dttypechild.newrow ();
Panax Notoginseng drchild5["typeid"] = 5;
drchild5["Typedetail"] = "pear";
DTTYPECHILD.ROWS.ADD (DRCHILD5);
Dttypechild.tablename = "fruit";
41
DataSet ds = new DataSet ();
DS. Tables.add (Dttypechild);
The return DS;
45}
46
47}
Background code:

1public Partial class AsyncVisitWebservice:System.Web.UI.Page
2{
3 Private King.webservice _ws;
4 private DataSet _ds;
5
6 protected void Page_Load (object sender, EventArgs e)
7 {
8 if (! IsPostBack)
9 {
this. Prerendercomplete + = new EventHandler (page_prerendercomplete);
One _ws = new King.webservice ();
_ws. getdatacompleted + = new King.getdatacompletedeventhandler (getdatacompleted);
_ws. URL = new Uri (Request.url, "Webservice.asmx"). ToString ();
_ws. useDefaultCredentials = true;
_ws. Getdataasync ();
16}
17}
18
void getdatacompleted (Object source, King.getdatacompletedeventargs E)
20 {
_ds = E.result;
22}
23
protected void Page_prerendercomplete (object sender, EventArgs e)
25 {
Num this. Gridview1.datasource = _ds;
Gridview1.databind ();
28}
29
public override void Dispose ()
31 {
if (_ws!= null)
_ws. Dispose ();
Base. Dispose ();
35}
36}
4. Implement asynchronous invocation function with PageAsyncTask (in addition to implementing asynchronous functions, you can also implement asynchronous operation wait time and time timeout operation)

A. Page Flag Plus properties: async= "true" asynctimeout= "5", add the following code:

1<%@ Page language= "C #" autoeventwireup= "true" codefile= "AsyncPageTask.aspx.cs" inherits= "Asyncpagetask" async= " True "asynctimeout=" 5%>

B. Background code

1public Partial class AsyncPageTask:System.Web.UI.Page
2{
3 Private WebRequest _request;
4
5 protected void Page_Load (object sender, EventArgs e)
6 {
7 PageAsyncTask task = new PageAsyncTask (
8 new BeginEventHandler (beginasyncoperation),
9 new EndEventHandler (Endasyncoperation),
New EndEventHandler (Timeoutasyncoperation),
One null
12);
13
RegisterAsyncTask (Task);
15}
16
IAsyncResult Beginasyncoperation (object sender, EventArgs E, AsyncCallback cb, Object State)
18 {
_request = WebRequest.Create ("http://blog.csdn.net/chengking");
Return _request. BeginGetResponse (CB, State);
21}
22
void Endasyncoperation (IAsyncResult ar)
24 {
-string text;
The using (WebResponse response = _request. EndGetResponse (AR))
27 {
The using (StreamReader reader = new StreamReader (response). GetResponseStream ()))
29 {
Text = reader. ReadToEnd ();
31}
32}
33
Lbdisplay.text = Text. ToString ();
35}
36
37//Time timed out operation
timeoutasyncoperation void (IAsyncResult ar)
39 {
Lbdisplay.text = "failture!";
41}
42}
(iii). Legacy issues.

The second way: the database object SqlCommand implement the function of asynchronous invocation

(corresponding to the page in the sample code: asyncvisitdatabase.aspx), sample code I have not been debugging success!

There is data in the database, but it is not shown in the GridView.

If you can pass the test, please advise!!!


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.