ASP Web Application Quick Start for. NET (2)
Application lifetime
An ASP. NET application is created when the server is requested for the first time. No ASP. NET code is executed before that. After accepting the first request, an HttpApplication instance pool is created and the Application_OnStart event is activated. The HttpApplication instance processes the request and subsequent requests until the final instance exits and then triggers the Application_OnEnd event.
Note that the Init and Dispose methods of HttpApplication are called in each instance. Therefore, the events of Application_OnStart and Application_OnEnd are called multiple times. In an ASP. NET
In application, only these events are shared in all HttpApplication instances.
Multithreading
If we use objects in the application range type, we should note that ASP. NET processes requests concurrently, so that the Application object can be accessed by multiple threads. Therefore, if the Code in the following example is accessed by different clients at the same time, it is dangerous and may not achieve the intended purpose. For ease of comparison, we listed the code written in three languages: VB, C #, and JScript:
C #
<%
Application ["counter"] = (Int32) Application ["counter"] + 1;
%>
VB
<%
Application ("counter") = CType (Application ("counter") + 1, Int32)
%>
JScript
<%
Application ("counter") = Int32 (Application ("counter") + 1 );
%>
To implement secure thread processing, we can use the Lock and Unlock methods to process this Application object. See the following code written in three languages: VB, C #, and JScript:
C #
<%
Application. Lock ();
Application ["counter"] = (Int32) Application ["counter"] + 1;
Application. UnLock ();
%>
VB
<%
Application. Lock ()
Application ("counter") = CType (Application ("counter") + 1, Int32)
Application. UnLock ()
%>
JScript
<%
Application. Lock ();
Application ("counter") = Int32 (Application ("counter") + 1 );
Application. UnLock ();
%>