************************************在Global.asax中如下************************

<%@ Import Namespace="System.Data.SqlClient" %>
起始:

void Application_Start(Object sender, EventArgs e)//当前应用程序启动这件事会发生
        {

 

      //SqlConnection con = new SqlConnection();       

      //con.ConnectionString = ConfigurationManager.ConnectionStrings["TongJiConnectionString"].ConnectionString;


            SqlConnection con=new SqlConnection("server=.;database=countPeople;uid=sa;pwd=;");
            con.Open();
            SqlCommand cmd=new SqlCommand("select * from countPeople",con);
            int count=Convert.ToInt32(cmd.ExecuteScalar());
            con.Close();
            Application["total"]=count;//Application是个全局变量,每个会话都可对他操作
            Application["online"]=0;
            

        }
 
        protected void Session_Start(Object sender, EventArgs e)//客户端一连接到服务器上,这个事件就会发生
        {
            Session.Timeout=1;
            Application.Lock();//锁定后,只有这个Session能够会话
            Application["total"]=(int)Application["total"]+1;
            Application["online"]=(int)Application["online"]+1;
            Application.UnLock();//会话完毕后解锁

        }

结尾:
void Session_End(Object sender, EventArgs e)
        {
            Application.Lock();
            Application["online"]=(int)Application["online"]-1;
            Application.UnLock();

        }

        protected void Application_End(Object sender, EventArgs e)
        {

 

        //SqlConnection con = new SqlConnection();       

         //con.ConnectionString = ConfigurationManager.ConnectionStrings["TongJiConnectionString"].ConnectionString; 


            SqlConnection con=new SqlConnection("server=.;database=countPeople;uid=sa;pwd=;");
            con.Open();
            SqlCommand cmd=new SqlCommand("update countPeople set num="+Application["total"],con);
            cmd.ExecuteNonQuery();
            con.Close();

        }

*****************************************在Aspx文件中如下*********************************
void Page_Load(object sender, System.EventArgs e)
        {
            this.lblTotal.Text=Application["total"].ToString();
            this.lblOnline.Text=Application["online"].ToString();
            // 在此处放置用户代码以初始化页面
        }
分类: ASP.NET