(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>