1.Application
Program-level variables share the global information between multiple sessions and requests.
Common methods Add () Lock () UnLock ()
Example: Show historical visitors and online numbers
Code in Globl.aspx
<span style= "FONT-SIZE:18PX;" > protected void Application_Start (object sender, EventArgs e)//set a global variable to implement user sharing {//applicat ion["Count"] = 0; Add data//Link database to Application object read data, generally written as configuration file, SqlConnection con = new SqlConnection ("Server =.; Database=mofang;user id=sa;password=123456; "); Con. Open (); SqlCommand cmd = new SqlCommand ("SELECT * from Tatalnum", con); int count = Convert.ToInt32 (cmd). ExecuteScalar ()); Con. Close (); application["Totalnum"]=count; application["Onlinenum"] = 0; } protected void Session_Start (object sender, EventArgs e)//global variable operation in one session {Session.Timeout = 1; Application.Lock (); Control access, add lock application["totalnum"] = (int) application["Totalnum"] + 1; Total plus 1 application["onlinenum"] = (int) application["Onlinenum"] + 1; Total plus 1 application.unlock (); Unlock,} protected void Session_End (object sender, EventArgs e)//session End {application["onlinenum"] = (int) App lication["Onlinenum"]-1; Total online minus 1} protected void Application_End (object sender, EventArgs e) {//LINK database will be Applicati on[data in "Totalnum"] is written to the database}</span>Web page Code
<span style= "FONT-SIZE:18PX;" > protected void Page_Load (object sender, EventArgs e) {this . Lbltotal.text = application["Totalnum"]. ToString (); This. Lblonline.text = application["Onlinenum"]. ToString (); } </span>
Show Results:
Analysis results:
First, display: The first time through the Web page, display 1th, 1, when the opening of a browser display 2, 2. Close the first browser refresh the second, supposedly the first browser session has ended, it should show 2, 1, but still display 2, 2.
Cause: The client closes the browser, the session ends, but the session does not end immediately at the server segment, but the server ends the session when there is no action within the specified time (timeout setting).
When all browsers are closed, the database has no data,
We will write the operation of the new database in the Application_End event, all only when the server side of the application to the end of the normal time to update the data to the database, the page closed the browser, but the server side of the program did not end!
Application objects--record historical visits