In-depth understanding of ASP. net mvc (9)

Source: Internet
Author: User

Series directory

Meaning of asynchronous request processing

Everyone knows that ASP.. Net processes requests through the thread pool. Each request requests an available thread from the thread pool to process the requests. After the request is processed, the thread resources will be returned to the thread pool. However, threads in the thread pool are mutually exclusive resources. When the number of requests of a website reaches a certain number at the same time, such resources will inevitably be exhausted, new requests can only be processed after a new thread is returned. Of course, this is not the worst case. Generally, each request only takes a short time. New requests do not have to wait too long. However, what if it takes a long time to process the request? For example, Io operations such as a time-consuming database query and an external web service request. Note that the I/O operations mentioned here do not occupy the threads in the ASP. NET thread pool or even the CPU resources of the local machine. Because of this, asynchronous processing of requests is particularly applicable in this case. When requests are processed asynchronously, the occupied thread returns the thread to the thread pool before the time-consuming Io operation starts. After the IO operation is completed, the thread pool requests a thread, restore the current httpcontext and process the IO operation results. This will not occupy valuable thread resources.

 

Asynchronous controller mechanism in MVC

MVC supports asynchronous request processing. You can use the following three methods:

    1. Implement a custom routehandler and return an ihttpasynhandler object for the gethttphandler method.
    2. Create a custom base class controller and implement iasynccontroller. iasynccontroller is the asynchronous version of icontroller.
    3. MVC has a built-inAsynccontroller, Which implements the precedingIasynccontroller, Asynchronous implementation can be achieved by simply inheriting asynccontroller.

The following describes only the third method. Assume that an action needs to call a web service and return the result after processing:

 
Public contentresult getphotobytag (string tag ){... using (VAR response = webrequest. create (URL ). getresponse () {// parse the response as xmlvar xmldoc = xdocument. load (xmlreader. create (response. getresponsestream ()));...}...}

Obviously, if the Web Request consumes 2 s, the request will hold this thread for at least 2 s. This synchronous processing method is obviously unreasonable. To perform asynchronous processing, you only need to follow the steps below:

1. Replace the base class controllerAsynccontroller

2. Create two matched actions: actionname async and actionname completed . actionname The async method must return void . Before starting a time-consuming Io operation internally, you must use asyncmanager. outstandingoperations. increment () registers and starts with the MVC Framework. After the IO method is returned, you can go to asyncmanager. save the parameters that you want to pass to the actionname completed method in the parameters dictionary. Finally, call asyncmanager. outstandingoperations. decrement () to notify the MVC Framework to complete the operation. At this time, the MVC Framework automatically calls actionname completed. actionname completed must return an actionresult like a common action. Therefore, the preceding Code must be rewritten as follows:

Public void getphotobytagasync (string tag) {// register with MVC to start asyncmanager. outstandingoperations. increment ();... webrequest request = webrequest. create (URL); // start an asynchronous web requestrequest. begingetresponse (asyncresult => {using (webresponse response = request. endgetresponse (asyncresult) {var xml = xdocument. load (xmlreader. create (response. getresponsestream ()));... // Save the result photourls in asyncmanager. asyncmanager in parameters. parameters ["photourls"] = photourls; // notify the MVC Framework to complete the operation and prepare to call completedasyncmanager. outstandingoperations. decrement () ;}}, null) ;}// like a common action, the photourls parameter here is stored in asyncmanager. match public contentresult getphotobytagcompleted (ienumerable <string> photourls) {return content (string. format (" 

Of course, you can set the timeout for asynchronous operations:

[Asynctimeout (10000)] // 10000 milliseconds equals 10 secondspublic void getphotobytagasync (string tag ){...}

If the above Code times out, it will throw a timeoutexception exception. We can handle it in the desired way.

When you use Asynchronous methods like begingetresponse and provide callback function parameters, you cannot control the thread on which the callback function is called. In most cases, it is not even on the ASP. NET working thread. Therefore, the callback function cannot be associated with the original httpcontext object.

Fortunately, asyncmanager providesSync ()It will initiate a delegate on the ASP. Net working thread and associate it with the original httpcontext object. It also ensures thread security:

Beginasyncoperation (asyncresult => {var result = endasyncoperation (asyncresult); // can't always access system. web. httpcontext. current from here... action dosomethingwithhttpcontext = () => {//... but can always access it from this delegate}; If (asyncresult. completedsynchronously) // already on an ASP. net threaddosomethingwithhttpcontext (); else // must switch to an ASP. net threadasyncmanager. sync (dosomethingwithhttpcontext); asyncmanager. outstandingoperations. decrement () ;}, null );

 

The above content is just an excerpt from the book. I have not studied asynchronous request processing in depth. I will try again later.

 

PS: I have been busy recently and have no time to focus on MVC. Sorry.

Labor fruit, reproduced please indicate the source: http://www.cnblogs.com/P_Chou/archive/2011/01/07/details-asp-net-mvc-09.html

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.