(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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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>