Address: http://www.cnblogs.com/brave-heart/articles/1218343.html
ASP. NET 2.0 provides a large number of new functions, including declarative Data Binding and master pages, member and role management services, and asynchronous pages. The following describes asynchronous pages.
When a user initiates a request to a page, Asp.net accepts the request and allocates a thread for the request from the thread pool. A common page (or a synchronized page)
This thread is retained during the request (this thread cannot be used for other requests). If the requested page needs to access WebService or ADO to call the database and wait for return (IO binding ),
The request thread is suspended before the call returns. At this point, you should know the problem. The number of available threads in the thread pool is limited,
If many users access this page together, all requests need to wait for the request thread to block until the call returns. If the number of available threads in the thread pool is 0
Other requests are queued to wait for the thread to release, so that the request can be processed after a long wait.
Asynchronous pages provide excellent solutions to problems caused by I/O binding requests. Page processing starts from the thread pool thread. When an asynchronous I/O operation starts to respond to ASP. NET
After the signal, the thread returns the thread pool. When this operation is completed, ASP. NET extracts another thread from the thread pool and processes the request. Because the thread pool thread obtains
It is more efficient to use, thus improving scalability. Threads pending for I/O completion can now be used to serve other requests. Direct beneficiaries are not long-lived.
I/O operations and therefore fast access to pipeline requests. Waiting for a long time to enter the pipeline will have a negative impact on the performance of such requests. (This section is from msdn)
To use an asynchronous page in ASP. NET 2.0, first add the async = "true" attribute in the @ page command of the aspx file, as shown below:
<% @ Page Language = "C #" autoeventwireup = "true" codebehind = "default. aspx. cs" async = "true" inherits = "webapplication1. _ default" %>
1. Use Page. addonprerendercompleteasync to implement the asynchronous page Function
Background asynchronous pageCode:
Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. IO;
Namespace webapplication1
{
Public partial class _ default: system. Web. UI. Page
{
Private system. net. webrequest _ request;
Protected void page_load (Object sender, eventargs E)
{
Page. addonprerendercompleteasync (New begineventhandler (beginmethod), new endeventhandler (endmethod ));
}
Iasyncresult beginmethod (Object sender, eventargs E, asynccallback CB, object state)
{
_ Request = system. net. webrequest. Create ("http://www.hyey.com ");
Return _ request. begingetresponse (CB, State );
}
Void endmethod (iasyncresult AR)
{
String text;
Using (system. net. webresponse response = _ request. endgetresponse (AR ))
{
Using (streamreader reader = new streamreader (response. getresponsestream ()))
{
TEXT = reader. readtoend ();
}
}
This. label1.text = text;
}
}
}
2. Call WebService asynchronously,
Net Framework 2.0 web service proxy supports two asynchronous calls to Web Services.
One is the begin and end methods for each method in the. NET Framework 1.x and 2.0 web service proxies.
The other is the new methodasync method and methodcompleted event provided only by the web service agent of. NET Framework 2.0.
If a Web Service has a method named Foo, besides the methods named Foo, beginfoo, and endfoo,
. NET Framework 2.0 web service proxy also includes methods named fooasync and events named foocompleted.
You can register the foocompleted event for processing.ProgramAnd call fooasync to asynchronously call Foo.
WebService method:
Using system;
Using system. Data;
Using system. Web;
Using system. collections;
Using system. Web. Services;
Using system. Web. Services. Protocols;
Using system. componentmodel;
Using system. Data. sqlclient;
Namespace webservice1
{
/// <Summary>
/// Summary of service1
/// </Summary>
[WebService (namespace = "http://tempuri.org/")]
[Webservicebinding (conformsto = wsiprofiles. basicprofile1_1)]
[Toolboxitem (false)]
Public class service1: system. Web. Services. WebService
{
[Webmethod]
Public dataset returnds ()
{
System. Threading. thread. Sleep (3000 );
string connstring = system. configuration. configurationmanager. connectionstrings ["sqlserverconnstring"]. tostring ();
sqlconnection con = new sqlconnection (connstring);
sqldataadapter da = new sqldataadapter ("select * From oauser", con );
dataset DS = new dataset ();
da. fill (DS);
return Ds;
}< BR >}
Background code:
Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Namespace webapplication1
{
Public partial class webform1: system. Web. UI. Page
{
Private localhost. service1 _ ws;
Private dataset _ DS;
Protected void page_load (Object sender, eventargs E)
{
If (! Page. ispostback)
{
This. prerendercomplete + = new eventhandler (page_prerendercomplete );
_ Ws = new webapplication1.localhost. service1 ();
_ Ws. returndscompleted + = new webapplication1.localhost. returndscompletedeventhandler (_ ws_returndscompleted );
_ Ws. url = "http: // localhost: 5983/service1.asmx"; // new uri (request. url, "service1.asmx"). tostring ();
_ Ws. usedefacrecredentials = true;
_ Ws. returndsasync ();
}
}
Void _ ws_returndscompleted (Object sender, webapplication1.localhost. returndscompletedeventargs E)
{
_ DS = E. result;
}
Protected void page_prerendercomplete (Object sender, eventargs E)
{
This. gridview1.datasource = _ DS;
This. gridview1.databind ();
}
}
}
3. Use pageasynctask to Implement Asynchronous calling
Background code:
Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. net;
Using system. IO;
Namespace webapplication1
{
Public partial class webform2: 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://www.hyey.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 ();
}
}
Lbdisplay. Text = text. tostring ();
}
// Time-out execution
Void timeoutasyncoperation (iasyncresult AR)
{
Lbdisplay. Text = "failture! ";
}
}
}
4. asynchronous call of the database object sqlcommand
Background code:
1 public partial class asyncvisitdatabase: system. Web. UI. Page
2 {
3 // define the data operation object
4 private sqlconnection _ connection;
5 private sqlcommand _ command;
6 private sqldatareader _ reader;
7
8 protected void page_load (Object sender, eventargs E)
9 {
10 if (! Ispostback)
11 {
12 // registration event page_prerender execution Method
13 This. prerendercomplete + = new eventhandler (page_prerendercomplete );
14
15/*** // register the in and end methods of asynchronous calls.
16 addonprerendercompleteasync (
17 new begineventhandler (beginasyncoperation ),
18 new endeventhandler (endasyncoperation)
19 );
20}
21}
22
23 // asynchronous call start method (when this method is executed, the current thread returns to the thread pool and waits for other request services ).
24 iasyncresult beginasyncoperation (Object sender, eventargs E, asynccallback CB, object state)
25 {
26 string connect = webconfigurationmanager. connectionstrings ["connectionstring"]. connectionstring;
27 _ connection = new sqlconnection (CONNECT );
28 _ connection. open ();
29 _ command = new sqlcommand ("select * from sales", _ connection );
30 return _ command. beginexecutereader (CB, State );
31}
32
33 // 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 this page request service ).
34 void endasyncoperation (iasyncresult AR)
35 {
36 _ reader = _ command. endexecutereader (AR );
37}
38
39 // 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.
40 protected void page_prerendercomplete (Object sender, eventargs E)
41 {
42 gridview1.datasource = _ reader;
43 gridview1.databind ();
44}
45
46 Public override void dispose ()
47 {
48 if (_ connection! = NULL)
49 _ connection. Close ();
50 base. Dispose ();
51}
52}