************************************在Global.asax中如下************************
起始:protected void Application_Start(Object sender, EventArgs e)//當前應用程式啟動這件事會發生
{
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();//會話完畢後解鎖
}
結尾:protected 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("server=.;database=countPeople;uid=sa;pwd=;");
con.Open();
SqlCommand cmd=new SqlCommand("updata countPeople set num="+Application["total"],con);
cmd.ExecuteNonQuery();
con.Close();
}
*****************************************在Aspx檔案中如下*********************************private void Page_Load(object sender, System.EventArgs e)
{
this.lblTotal.Text=Application["total"].ToString();
this.lblOnline.Text=Application["online"].ToString();
// 在此處放置使用者代碼以初始化頁面
}
NinetyNine原創