使用application对象显示在线人数,Global.asax文件
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Security;using System.Web.SessionState;namespace ManageStudent{ public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { //在应用程序启动时运行的代码 //初始化变量:UserCount() Application.Lock();//临界变量,使用加锁功能 Application["UserCount"] = 0; Application.UnLock();//临界变量被解锁 } protected void Session_Start(object sender, EventArgs e) { //在新会话启动时运行的代码 //用户数量加1 Application.Lock(); Application["UserCount"] = Int32.Parse(Application["UserCount"].ToString()) + 1; Application.UnLock(); } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { //在新会话结束时运行的代码 //注意:只有在web.config文件中的sessionstate模式设置为InProc时。 //如果会话模式设置为StateServer或SQLServer,则不会引发该事件 //用户数量减一 Application.Lock(); Application["UserCount"] = Int32.Parse(Application["UserCount"].ToString())- 1; Application.UnLock(); } protected void Application_End(object sender, EventArgs e) { } }}
接下来,需要在web.config配置文件中<system,web>标签内添加如下一条语句
<sessionState mode="InProc"/>
在ApplicationDemo.aspx中写入代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ApplicationDemo.aspx.cs" Inherits="ManageStudent.ApplicationDemo" %>
在cs文件中,写入代码,用于显示在线人数
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace ManageStudent{ public partial class ApplicationDemo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { lblUserCount.Text = "网站在线人数:" + Application["UserCount"] + "人"; } } protected void btnLogout_Click(object sender, EventArgs e) { //销毁Session Session.Abandon(); } }}