Number of online user visits. That is to say, to write a counter for the website, the initial value of the counter is 0. When the website starts running (Application_Start), statistics are started, when a user accesses the server (Session_Start), the counter is incremented by 1. When the user leaves the server (Session_End), the counter is reduced by 1.
Define a counter at the beginning of the program. The initial value is 0.
| The code is as follows: |
Copy code |
Sub Application_Start (ByVal sender As Object, ByVal e As EventArgs) 'Code that runs on application startup Application ("OnlineVisitors") = 0 End SubView Code |
When a user accesses a website:
| The code is as follows: |
Copy code |
Sub Session_Start (ByVal sender As Object, ByVal e As EventArgs) 'Code that runs when a new session is started Application. Lock () Application ("OnlineVisitors") = DirectCast (Application ("OnlineVisitors"), Integer) + 1 Application. UnLock () End Sub
|
When a user leaves the website:
| The code is as follows: |
Copy code |
Sub Session_End (ByVal sender As Object, ByVal e As EventArgs) 'Code that runs when a session ends. 'Note: The Session_End event is raised only when the sessionstate mode 'Is set to InProc in the Web. config file. If session mode is set to StateServer 'Or SQLServer, the event is not raised. Application. Lock () Application ("OnlineVisitors") = DirectCast (Application ("OnlineVisitors"), Integer)-1 Application. UnLock () End Sub
|
In the above two Session_Start and Session_End methods, Insus. NET has Application. lock and Application. the Unlock method is used to prevent multiple threads from changing this variable at the same time. When changing the counter, Lock the variable first, and then Unlock the variable.
Save the Global. asax file and display the number of online visitors on the webpage:
| The code is as follows: |
Copy code |
<% = Application ("OnlineVisitors"). ToString () %> |
During the test, Insus. NET uses two browsers to allow websites to access different process visitors. Each browser opens a different window and obtains the data variables.