I read two well-written blog posts a few days ago: detailed explanation of. Net Asynchronization and detailed explanation of ASP. NET Asynchronization.ArticleThe author explains in detail how. and how to asynchronously process requests in Asp.net. at the beginning, I couldn't understand a lot of things, or I couldn't figure it out. by taking advantage of this, I reviewed the Asp.net webform model again, and then read the CLR via C #, right. net asynchronous processing. it took several days to understand the entire processing mechanism.
1. Asp.net webform general process
After IIS receives a request from the client, if it finds that this is a request for an Asp.net resource, it calls the httpruntime object and submits it.. net. httpruntime creates an httpcontext object. this context object is subject to the entire lifecycle of the request. then obtain an httpapplication object instance. please note that here the httpcontext object is created, and httpapplication is obtained. because HTTP requests are stateless, in the view of IIS, each request of the same client is still a brand new request. therefore, the context object needs to be re-created each time. the httpapplication object is the pipeline model object that processes requests. As long as the server configuration does not change, the components of this pipeline model will not change, therefore, you do not need to re-create each time. to achieve high-performance image reuse. there is an httpapplication Object pool. every time the request is processed, the httpapplication object will return to the pool again to wait for the next call.
As mentioned above, the httpapplication object is a pipeline model object, so the next step is to each httpmodule and the ihttphandler object that actually processes the request, and then return to the httpapplication object through each httpmodule object, and finally send a response to the client.
Ii. Closure
The so-called closure means that the variables used are out of its scope, but because of the context relationship with the scope, they can continue to use a function object defined in the above environment in the current environment. this stuff is common in dynamic languages, such as JavaScript, such:
FunctionF1 (){VaRN = 999;Return Function(){ReturnN ;}}VaRA =F1 (); alert (());
The local variable n is the closure.
In. net, there are similar things. For example, anonymous delegation is the most common. So how to implement the closure syntax in. Net? The Decompilation tool will be used here. I use reflector. remember to make some settings: Open the "View" menu --> select "options", first remove the check box before show PDB symbols, and then change the drop-down box after optimization ".. NET 1.0"
(1) do not reference external variables
ClassTest {Public VoidGetdata1 () {Action Action1=NewAction () => console. writeline ("1"));}}
DecompiledCodeAs follows:
[Compilergenerated] Private Static Action CS $ <> 9 _ cachedanonymousmethoddelegate7; [compilergenerated] Private Static Void <Getdata1> B _ 6 () {console. writeline ( " 1 " );} Public Void Getdata1 () {Action action = (CS $ <> 9 _ cachedanonymousmethoddelegate7! = Null )? CS $ <> 9 _ cachedanonymousmethoddelegate7: (CS $ <> 9 _ cachedanonymousmethoddelegate7 = New Action (test. <getdata1> B _ 6 ));}
It can be seen that this is the most normal processing, defining a static action delegate, a static method, and then associating.
(2). Reference local variables
ClassTest {Public VoidGetdata2 (){IntI =10;IntJ =20; Action Action2=NewAction () => console. writeline (I +J ));}}
The decompiled code is as follows:
[Compilergenerated] Private Sealed Class <>C _ displayclass5 { // Fields Public Int I; Public Int J; // Methods Public Void <Getdata2> B _ 4 () {console. writeline (( Int )( This . I + This . J ));}} Public Void Getdata2 (){ <> C _ displayclass5 class2 = New <> C _ displayclass5 (); class2. I = 10 ; Class2.j = 20 ; Action Action = New Action (class2. <getdata2> B _ 4 );}
As you can see, when a local variable is referenced, the anonymous method in the Action delegate is no longer compiled as a static method of the class, but compiled into an internal class, then, two public fields I and j are defined for this internal class, which correspond to the referenced I and j respectively, and the actual packaging of action is the method of this internal class <getdata2>B _ 4.
(3). Reference the attributes of the class
Class Test { Public Int Number { Get ; Set ;} Public Void Getdata3 (){ Int I =10 ; Int J = 20 ; Data Data = New Data () {sum = 10 }; Action action3 = New Action () => console. writeline (I + J + number + Data. Sum ));}} Class Data { Public Int Sum {Get ; Set ;}}
The decompiled code is as follows:
[Compilergenerated] Private Sealed Class <> C _ displayclass2 { // Fields Public Test <> 4 _ this; Public Data data; Public Int I; Public Int J; // Methods Public Void <Getdata3> B _ 1 () {console. writeline (( Int )( This . I + This . J + This . <> 4 _ this. Number + This . Data. Sum ));}} Public Void Getdata3 (){ <> C _ displayclass2 class2 = New <> C _ displayclass2 (); class2. <> 4 _ this = This ; Class2. I = 10 ; Class2.j = 20 ; Data Data =New Data (); Data. Sum = 10 ; Class2.data = Data; action Action = New Action (class2. <getdata3> B _ 1 );}
As you can see, the processing method is basically the same as that in the second case, except that a public field of the class is added to the internal class.
It is basically clear here ,. net implements closures by constructing an anonymous class and referencing all the resources used to the shared public fields of the same name of the anonymous class. as shown in Example 3 above, I, j, number, and sum seem to be referenced from the test class. In fact, they are referenced by their own anonymous classes. these objects still do not violate the lifecycle. net object lifecycle rules.
Iii. From synchronous to asynchronous
By default, a Web server can respond to multiple client requests at the same time. Obviously, the web server runs in a multi-threaded environment. it is used to increase processing speed and save resources. net thread pool. whenever Asp.net processes a client request, it extracts a thread from the thread pool. when the processing is complete and relevant information is returned to the client, this thread returns to the pool to prepare for the next call.
If the data requested by the client is very complex and requires a long period of computing, this thread will be occupied all the time. if the server needs to process new requests, it must create a new thread. the more threads are occupied, the more memory is occupied, the more times the CPU context switches, and the lower the performance.
In addition, it should be noted that the thread isProgramThe basic unit of processing. We often say that the stack is on the thread. all resources in the program must be attached to a thread, as shown in:
First, the thread pool schedules a thread for processing Asp.net requests. this thread processes all objects involved in the Asp.net lifecycle. after the result is returned to the client, return to the thread pool again to wait for a new call.
To improve the performance of requests that may occupy threads for a long time,. Net proposes the concept of asynchronous processing, as shown in:
The ihttphandler object is the core object for processing requests. since the processing time is too long, let him change from the original synchronous processing to asynchronous processing, and return valuable thread resources to the thread pool. after the asynchronous processing is complete, obtain a new thread from the thread pool to complete the output.
Iv. asynchronous mode
In. in net, there are two asynchronous Methods: multithreading and Completion Ports, or, according to CLR via C #, computing restrictions and I/O restrictions. multithreading, as its name implies, is the use of multiple threads to execute tasks in parallel, which is generally related to logical computing. The main resource consumption is the CPU and memory, so it is also called the computing limit; the completion port uses the characteristics of the operating system and the driver to guide the hardware to complete tasks in parallel. Compared with network transmission or file read/write, it mainly consumes hardware resources, so I/O restrictions.
To implement the two asynchronous methods ,. NET provides a variety of asynchronous programming models: thread (pool), thread pool-based timer, task, registerwaitforsingleobject, iasyncresult APM, EAP (Event-based), asyncenumerator, and so on. there are two main types: thread (pool) and iasyncresult APM. the former mainly provides support for multithreading, and the latter mainly provides support for the completion port. of course, you can use the completion port in the thread (pool) and use the thread (pool) in the iasyncresult APM.
5..asp.net asynchronous
The core asynchronous interface of Asp.net is ihttpasynchandler. its asynchronous model is iasyncresult APM. this interface has two methods: iasyncresult beginprocessrequest (httpcontext context, asynccallback CB, object extradata) and void endprocessrequest (iasyncresult result), as shown in:
As you can see, the httpapplication object calls the beginprocessrequest method of the ihttpasynchandler object and uses a thread. after the beginprocessrequest method initiates an asynchronous call, this thread returns to the thread pool. after the asynchronous call is complete, obtain a thread from the thread pool to call a callback function, and then call the endprocessrequest method. below are a few points worth noting.
(1). Object lifecycle.
As mentioned above, all resources in the program must be attached to a thread. after the Web thread finishes calling the beginprocessrequest method of the ihttpasynchandler object, it returns to the thread pool. Then, whether the httpapplication object has been returned to the object pool, and another thread calls the httpapplication object callback method, is this object the same as the previous object? After my research, the conclusion is: they are the same object. Asp.net asynchronously informs the asynchronous completion through the callback method, so it is necessary to pass the delegate of the httpapplication object callback method into asynchronous execution. on the one hand, this incoming process is actually a closure process: asynchronous execution has a delegate of the httpapplication object, and the httpapplication object will not return or die with the regression of the Web thread; another method, even if you do not pass in the delegate and do not constitute a closure, the httpapplication object will not return or die with the regression of the Web thread. It will not die because the thread of the httpapplication Object pool maintains its reference, if you do not call back the delegate, the httpapplication object will not return to the object pool intelligently.
This raises another question: what is the cost of improving the Web server throughput asynchronously. one of the answers I think is the increase in memory usage. it turns out to be a request to an httpapplication object and a thread. The request: object: thread =. When the thread is large enough, the extra requests should be queued. Now all requests can come in, the result is that the httpapplication object increases and waits for processing, and the thread processes the tasks to be processed. The increase of the httpapplication Object pool object is used in exchange for the decrease of the thread pool thread. in fact, I think this is worth it, because the number of httpapplication objects increases, but it only occupies more memory, and the number of threads in the thread pool increases, it takes up more memory and more CPU resources.
(2) Why is the Asp.net asynchronous model iasyncresult APM.
In. net, a CLR has only one thread pool. this means that the Web thread comes from this unique thread pool, this also means that the thread sources of other thread pool operations are the same as those of the Web thread. The Asp.net asynchronous intent is to release the thread as much as possible and occupy less threads, however, if your Asynchronization is completed by another thread pool thread, what is the difference between the usage of the thread pool thread and the usage of the same thread, A request still occupies one thread, but is combined with two threads. its performance should be lower than using a thread because it increases the CPU context switching. I think this is one of the reasons why the Asp.net team chose the iasyncresult APM asynchronous model.
Of course, this does not mean that multithreading cannot be used to complete Asp.net Asynchronization. in details ASP. net asynchronous in this blog post message, I saw a garden friend cited some foreign data and summed up the conclusion. I think it is very good. in fact, apart from the thread pool, the thread can also be built by itself, or the logic to be processed can be sent to other machines for processing. as long as the thread used does not come from the thread pool, it will not occupy the Web thread or conflict with it. the Web server concurrency can be increased. of course, as mentioned above, the more threads, the better. thread creation and destruction occupy system resources and increase the CPU context switching rate. the concurrency of web servers does not rise in a straight line, but is an arc. The growth rate slows down to a certain extent or even begins to decrease. in the case of a single server, the increase in concurrency is limited. if you really want to achieve high concurrency, you can use a separate server, as park friends said.
(3) Two threads
When thread is used for asynchronous implementation, at least two threads are involved. as shown in, the implementation of each object in the Asp.net pipeline model goes to the beginprocessrequest method of the ihttpasynchandler object, which is a thread in blue; asynchronous execution, and the callback method of the httpapplication object, the endprocessrequest method of the ihttpasynchandler object and the execution of each object in the Asp.net pipeline model is another thread, which is represented in purple.
Vi. Application
The most frequently seen applications are persistent connections. there are many examples on the Internet. net Asynchronization this blog post has also been written a lot and is well written. I will not talk about it here.
The above is my research experience. I have carefully studied the CLR via C # book, and I have also referred to the articles of many garden friends. some of the conclusions come from references, and some are their own. you need to open your eyes. if something is wrong, please leave a message to inform us that the level is limited. Please advise me more!
References:
1. Details about. Net Asynchronization
2. ASP. NET Asynchronization
3. Preliminary understanding and understanding of ASP. NET underlying layer and various components
4. C # And closure
5. Use reflector to see the "closure" clearly
6. Use ihttpasynchandler to implement comet
7. Asp.net webform asynchronous page you should know