Document directory
- I. Use Page. addonprerendercompleteasync to implement the asynchronous page function.
- 2. The database object sqlcommand implements the asynchronous call function.
- 3. Implement Asynchronous WebService call
- 4. Use pageasynctask to Implement Asynchronous calling (in addition to implementing asynchronous functions, asynchronous operation waiting time and time-out operations can also be implemented)
Asp.net 2.0 Asynchronous Operation page (1). briefly introduces the implementation principle
On the left, the asynchronous page function is not used for execution (Asp.net 1.0 is usually used), and on the right, the asynchronous page execution process is used (Asp.net 2.0 new feature ).
(Asp.net 1.0 general processing process) (use Asp.net 2.0 to add a feature for asynchronous page processing)
As shown in the figure on the left, a thread always serves requests on the same page during the entire request process.
As shown in the right figure, different threads can request services for this page during a page request process.
Obviously, when the number of client requests is large in the figure, the overall efficiency of the website is high because:
1. when an asynchronous page is not used, a thread can only serve the request of the same page. this thread remains in the waiting status even when other I/O operations are processed during the page request process.
When this page is used up, it is placed back to the thread pool. The number of threads is limited! Therefore, putting the thread back into the thread pool in time can greatly improve the system performance!
2. When the asynchronous page function is used, for example, thread1 starts to serve the page, but when the page handles other things (such as I/O or calls other
When thread1 is put back into the thread pool, thread1 can serve other page requests. When this page returns after performing its own operations,
Thread2 then serves the page request, not using the original thread thread1. this will improve the scalability of the website.
(2). example I. Use Page. addonprerendercompleteasync to implement the asynchronous page Function
A. Page flag adds attribute: async = "true". The code after adding is as follows:
<% @ Page Language = "C #" autoeventwireup = "true"
Codefile = "asyncpage. aspx. cs"
Inherits = "_ default" async = "true" %>
B. Code related to the background asynchronous page:
Private webrequest _ request;
Protected void page_load (Object sender, eventargs E)
...{
// Register the begin and end methods of asynchronous calls.
Addonprerendercompleteasync (
New begineventhandler (beginasyncoperation ),
New endeventhandler (endasyncoperation)
);
}
// Asynchronous call start method (when this method is executed, the current thread returns to the thread pool and waits for other request services ).
Iasyncresult beginasyncoperation (Object sender, eventargs E, asynccallback CB, object state)
...{
_ Request = webrequest. Create ("http://blog.csdn.net/chengking ");
Return _ request. begingetresponse (CB, State );
}
// The receiving method after the asynchronous call is completed (after the asynchronous operation is completed, a thread from the thread pool will be retrieved again for the webpage request service ).
Void endasyncoperation (iasyncresult AR)
...{
String text;
Using (webresponse response = _ request. endgetresponse (AR ))
...{
Using (streamreader reader = new streamreader (response. getresponsestream ()))
...{
TEXT = reader. readtoend ();
}
}
This. lboupput. Text = text;
}
2. The database object sqlcommand implements the asynchronous call function.
A. Page flag adds attribute: async = "true". The code after adding is as follows:
<% @ Page Language = "C #" autoeventwireup = "true"
Codefile = "asyncpage. aspx. cs"
Inherits = "_ default" async = "true" %>
B. Background code
Public partial class asyncvisitdatabase: system. Web. UI. Page
...{
// Define the data operation object
Private sqlconnection _ connection;
Private sqlcommand _ command;
Private sqldatareader _ reader;
Protected void page_load (Object sender, eventargs E)
...{
If (! Ispostback)
...{
// Registration event page_prerender execution Method
This. prerendercomplete + = new eventhandler (page_prerendercomplete );
/** // Register the begin and end methods of asynchronous calls.
Addonprerendercompleteasync (
New begineventhandler (beginasyncoperation ),
New endeventhandler (endasyncoperation)
);
}
}
// Asynchronous call start method (when this method is executed, the current thread returns to the thread pool and waits for other request services ).
Iasyncresult beginasyncoperation (Object sender, eventargs E, asynccallback CB, object state)
...{
String connect = webconfigurationmanager. connectionstrings ["connectionstring"]. connectionstring;
_ Connection = new sqlconnection (CONNECT );
_ Connection. open ();
_ Command = new sqlcommand ("select * from sales", _ connection );
Return _ command. beginexecutereader (CB, State );
}
// The receiving method after the asynchronous call is completed (after the asynchronous operation is completed, a thread from the thread pool will be retrieved again for the webpage request service ).
Void endasyncoperation (iasyncresult AR)
...{
_ Reader = _ command. endexecutereader (AR );
}
// The method of executing the event page_prerender when the execution is complete. Here, you can assign the return result of the asynchronous call to the control on the page or other aftercare operations.
Protected void page_prerendercomplete (Object sender, eventargs E)
...{
Gridview1.datasource = _ reader;
Gridview1.databind ();
}
Public override void dispose ()
...{
If (_ connection! = NULL)
_ Connection. Close ();
Base. Dispose ();
}
}
3. Implement Asynchronous WebService call
A. Page flag adds attribute: async = "true". The code after adding is as follows:
<% @ Page Language = "C #" autoeventwireup = "true"
Codefile = "asyncpage. aspx. cs"
Inherits = "_ default" async = "true" %>
B. Background code
WebService method (generate data ).
Public class WebService: system. Web. Services. WebService ...{
Public WebService ()...{
// Uncomment the following line if using designed components
// Initializecomponent ();
}
[Webmethod]
Public dataset getdata ()...{
Return createdata ();
}
Private dataset createdata ()
...{
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 ();
Drchild5 ["typeid"] = 5;
Drchild5 ["typedetail"] = "Pear ";
Dttypechild. Rows. Add (drchild5 );
Dttypechild. tablename = "Fruit ";
Dataset DS = new dataset ();
DS. Tables. Add (dttypechild );
Return Ds;
}
}
Background code:
Public partial class asyncvisitwebservice: system. Web. UI. Page
...{
Private King. WebService _ ws;
Private dataset _ DS;
Protected void page_load (Object sender, eventargs E)
...{
If (! Ispostback)
...{
This. prerendercomplete + = new eventhandler (page_prerendercomplete );
_ Ws = new king. WebService ();
_ Ws. getdatacompleted + = new king. getdatacompletedeventhandler (getdatacompleted );
_ Ws. url = new uri (request. url, "WebService. asmx"). tostring ();
_ Ws. usedefacrecredentials = true;
_ Ws. getdataasync ();
}
}
Void getdatacompleted (Object source, King. getdatacompletedeventargs E)
...{
_ DS = E. result;
}
Protected void page_prerendercomplete (Object sender, eventargs E)
...{
This. gridview1.datasource = _ DS;
Gridview1.databind ();
}
Public override void dispose ()
...{
If (_ ws! = NULL)
_ Ws. Dispose ();
Base. Dispose ();
}
}
4. Use pageasynctask to Implement Asynchronous calling (in addition to implementing asynchronous functions, asynchronous operation waiting time and time-out operations can also be implemented)
A. Page flag adds a property: async = "true" asynctimeout = "5". The code after adding the property is as follows:
1 <% @ page Language = "C #" autoeventwireup = "true"
Codefile = "asyncpagetask. aspx. cs" inherits = "asyncpagetask" async = "true"
Asynctimeout = "5" %>
B. Background code
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://blog.csdn.net/chengking ");
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 ();
}
}
Lbdisplay. Text = text. tostring ();
}
// Time-out execution
Void timeoutasyncoperation (iasyncresult AR)
...{
Lbdisplay. Text = "failture! ";
}
} Method 2: implement the asynchronous call function of the database object sqlcommand
Private webrequest _ request;
Private sqlconnection _ connection;
Private sqlcommand _ command;
Private sqldatareader _ reader;
Datatable table = new datatable ();
Protected void page_load (Object sender, eventargs E)
...{
/// Register the begin and end methods of asynchronous calls.
If (! Ispostback)
...{
// Execute the registration event page_prerender when the execution is complete (in fact, this one does not need to be written. When debugging, you will find that page_prerendercomplete runs twice, because the page should already run when it is opened)
// This. prerendercomplete + = new eventhandler (page_prerendercomplete );
/**//**//**//**/
/** // Register the begin and end methods of asynchronous calls.
Addonprerendercompleteasync (
New begineventhandler (beginasyncoperation), new endeventhandler (endasyncoperation ));
}
}
// Asynchronous call start method (when this method is executed, the current thread returns to the thread pool and waits for other request services ).
Iasyncresult beginasyncoperation (Object sender, eventargs E, asynccallback CB, object state)
...{
// _ Request = webrequest. Create ("http://blog.csdn.net/chengking ");
// 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 );
}
// The receiving method after the asynchronous call is completed (after the asynchronous operation is completed, a thread from the thread pool will be retrieved again for the webpage request service ).
Void endasyncoperation (iasyncresult AR)
...{
_ Reader = _ command. endexecutereader (AR );
// To ensure that the data is displayed in dataview
Table. Load (_ reader );
}
Protected void page_prerendercomplete (Object sender, eventargs E)
...{
This. gridview1.datasource = table;
This. gridview1.databind ();
}