Asynchronous page instance in ASP. NET 2.0

Source: Internet
Author: User

Asynchronous page instance in ASP. NET 2.0 (09:35:17)
Category:Asp.net
 

ASP. Network 2.0Asynchronous page in

 

ASP. NETPage running principle

-Iis isapi extension

-ASP. NET Workflow

-IIS application pool (process pool)

-Isolation level

-   Processing of ASP. NET Web requests

 

ASP. NET Page running principle

 InASP. NET 1.xAsynchronous page

-Implement the ihttpasynchandler Interface

-Custom Thread Pool

-Disadvantages:

"Complicated implementation

"No system mechanism supported

ASP. Network 2.0Asynchronous page in

-Set

<% @ Page async = "true"... %>

-Code

Addonprerendercompleteasync (

New begineventhandler (mybeginmethod ),

New endeventhandler (myendmethod)

);

 

Asynchronously call Web Services

Proxy. foocompleted + = new foocompletedeventhandler(Onfoocompleted );

Proxy. fooasync (...);

...

Void onfoocompleted (Object source, foocompletedeventargs E)

{

// Called when Foo completes

}

[Instance Code]

First, if you want to make asynchronous calls on the page, you must set the async attribute of the page to true:

<% @ Page Language = "C #" async = "true" autoeventwireup = "true"Codefile = "default. aspx. cs" inherits = "_ default" %>

First, let's take a look at the code of a simple asynchronous call on the page to obtain the target webpage:

Using system. Text. regularexpressions; // reference space of the Regular Expression

 

System. net. webrequest myrequest;

 

Protected void page_load (Object sender, eventargs E)

{

Label1.text = "page_load: thread #" + system. Threading. thread. currentthread. gethashcode ();

   Begineventhandler bH = new begineventhandler (this. begingetasyncdata );

   Endeventhandler Eh = new endeventhandler (this. endgetasyncdata );

  

 AddonprerendercompleteasYNC (BH, eh );

   String address = "http://msdn.microsoft.com /";

   Myrequest = system. net. webrequest. Create (Address );

}

 

Protected iasyncresult begingetasyncdata (Object SRC, eventargs ARGs, asynccallback CB, object state)

{

       Label2.text = "begingetasyncdata: thread #" + system. Threading. thread. currentthread. gethashcode ();

       Return myrequest. begingetresponse (CB, State );

}

Protected void endgetasyncdata (iasyncresult AR)

{

   Label3.text = "endgetasyncdata: thread #" + system. Threading. thread. currentthread. gethashcode ();

   // System. net. webresponse myresponse = myrequest. endgetresponse (AR );

  // Result. Text = new streamreader (myresponse. getresponsestream (). readtoend ();

   // Myresponse. Close ();

   String STR = "";

   Using (system. net. webresponse response = myrequest. endgetresponse (AR ))

   {

       Using (streamreader reader = new streamreader (response. getresponsestream ()))

       {

           STR = reader. readtoend ();

       }

   }

   RegEx Reg = new RegEx ("href/S * = // s */" ([^/"] *)/" ", regexoptions. ignorecase );

   Matchcollection matchs = reg. Matches (STR );

   Stringbuilder sb = new stringbuilder (1024 );

   Foreach (match in matchs)

   {

       SB. append (match. Groups [1]);

       SB. append ("<br/> ");

   }

   Result. Text = sb. tostring ();

}

Next let's look at how to implement the same function by registering an asynchronous task on the page:

Protected void page_load (Object sender, eventargs E)

{

    Pageasynctask task = new pageasynctask (

          New begineventhandler (begingetasyncdata ),

          New endeventhandler (endgetasyncdata ),

          New endeventhandler (timeouthandler ),

          Null );

   Registerasynctask (task );

}

 

Protected iasyncresult begingetasyncdata (Object SRC, eventargs ARGs, asynccallback CB, object state)

{

   String address = "http://msdn.microsoft.com /";

   Myrequest = system. net. webrequest. Create (Address );

 

   Return myrequest. begingetresponse (CB, State );

}

 

Protected void endgetasyncdata (iasyncresult AR)

{

   // Equivalent to the above

}

 

Protected void timeouthandler (iasyncresult AR)

{

   Response. Write ("Timeout !!! ");

}

Let's look at an example of asynchronous callback between the server and the database:

Private sqlcommand cmd;

Private sqldatareader SDR;

 

Protected void page_load (Object sender, eventargs E)

{

   This. prerendercomplete + = new eventhandler (page_prerendercomplete );

 

   Begineventhandler bH = new begineventhandler (this. begingetasyncdata );

   Endeventhandler Eh = new endeventhandler (this. endgetasyncdata );

 

   AddonprerendercompleteasYNC (BH, eh );

}

 

Protected iasyncresult begingetasyncdata (Object SRC, eventargs ARGs, asynccallback CB, object state)

{

   // The server accesses the database asynchronously. Be sure to have async = true;

   Sqlconnection SC = new sqlconnection ("...; Async = true ;");

   SC. open ();

   Cmd = new sqlcommand ("select * from employee", SC );

   Return cmd. beginexecutereader (CB, State );

}

 

Protected void endgetasyncdata (iasyncresult AR)

{

   SDR = cmd. endexecutereader (AR );

}

 

Protected void page_prerendercomplete (Object sender, eventargs E)

{

   This. gridview1.datasource = SDR;

   This. gridview1.databind ();

}

Finally, let's look at the example of asynchronous callback with Web Services.

 

[Msdn annotation]

1.     Asynchronous taskPageasynctask

ASP. NET 2.0 allows you to register multiple tasks on the page and run these tasks asynchronously before the page is displayed. If the task process is slow and you do not want to delay other processes when running it, you can specify to run the task asynchronously. Asynchronous tasks can be executed in parallel or in sequence.

The pageasynctask object must be registered to the page through the registerasynctask method. The page itself does not require asynchronous processing to execute asynchronous tasks. You can set the async attribute to true (as shown in the following code example) or false in the instructions on the page, and the asynchronous task will still be processed asynchronously:

<% @ Page async = "true" %>

When the async attribute is set to false, the thread on the execution page will be blocked before all asynchronous tasks are completed.

If an asynchronous task registered before the prerendercomplete event has not yet been executed, it will be automatically executed by the page. The asynchronous task registered after the prerendercomplete event must pass the executeregisteredasynctaThe SKS method is explicitly executed. ExecuteregisteredasynctaThe SKS method can also be used to start a task before the prerendercomplete event. ExecuteregisteredasynctaAll unexecuted registered asynchronous tasks on the SKS method execution page.

By default, an asynchronous task times out if it is not completed within 45 seconds. You can specify different timeout values in the web. config file or page command. The <pages> section of the web. config file contains the asynctimeout attribute, as shown below.

<System. Web>

<Pages asynctimeout = "30"> </pages>

</System. Web>

The page directive contains the asynctimeout attribute.

<% @ Page asynctimeout = "30" %>

2.      Addonprerendercompleteasync:

Use addonprerendercompleteasThe YNC method adds a handler to an asynchronous webpage.

Multiple asynchronous handlers can be registered, but only one handler can be run at a time. To process multiple asynchronous methods at the same time, use a single begineventhandler method and start multiple asynchronous operations from the handler.

The asynchronous handler is called between the prerender and prerendercomplete events.

First, run all page events (through the prerender event), and then call each registered begineventhandler method. When the processing program is complete, call the corresponding endeventhandler method. If multiple asynchronous handlers exist, the next handler is called.

After a registered asynchronous event handler is called, other page events are called from the prerendercomplete event.

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.