利用Application物件顯示當前線上人數。
(1)在會話開始和結束時,一定要進行加鎖和解鎖操作。由於多個使用者可以共享Application物件,因此加鎖是必要的,這樣可以保證在同一時刻只有一個客戶可以修改和存取Application物件的屬性。如果加鎖後,遲遲不給開鎖,會導致使用者無法訪問Application物件。我們可以使用物件的Unlock方法來解除鎖定。
(2)我們是根據使用者建立和退出會話來實現線上人數的增加、減少的,如果使用者沒有關閉瀏覽器,而直接進入其他URL,則這個會話在一定時間內是不會結束的,所以對線上使用者的統計存在一定的偏差。當然我們可以在Web.config檔案中對會話Session的失效時間Timeout來設定,預設值為20分鐘,最小值為1分鐘。
(3)只有在Web.config檔案中的sessionstate模式設定為InProc時,才會引發Session_End事件。如果會話模式為StateServer或SQLServer,則不會引發該事件。
我們在網站中新增一個Global.asax全域性應用程式檔案.
注:WEB應用程式我們可以把一些全域性變數儲存在Global.asax檔案下,對於VS2003下建立的WEB應用程式會自動生成Global.asax檔案,而VS2005則可以通過新增新項-->全域性應用程式類,來建立Global.asax檔案.
Global.asax檔案程式碼如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
namespace Demo
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
Application["count"] = 0;
}
protected void Application_End(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
Session.Timeout = 1;
Application.Lock();
Application["count"] = (int)Application["count"] + 1;
Application.UnLock();
}
protected void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["count"] = (int)Application["count"] - 1;
Application.UnLock();
}
}
}
頁面後臺程式碼如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace Demo
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Label1.Text = "當前線上人數:" + Application["count"].ToString();
}
}
}
頁面前臺程式碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo._Default" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>無標題頁</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label" Width="128px"></asp:Label></div>
</form>
</body>
</html>