Asp.net利用Application与Session统计网站在线人数和访问总人数
protected void Application_Start(Object sender, EventArgs e) { SqlConnection con=new SqlConnection("server=localhost;database=countPeople;uid=sa;pwd=sa;"); con.Open(); SqlCommand cmd=new SqlCommand("select * from countPeople",con); int count=Convert.ToInt32(cmd.ExecuteScalar()); con.Close(); Application["totol"]=count; Application["online"]=0; } protected void Session_Start(Object sender, EventArgs e) { Session.Timeout=1; Application.Lock(); Application["totol"]=(int)Application["totol"]+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=localhost;database=countPeople;uid=sa;pwd=sa;"); con.Open(); SqlCommand cmd=new SqlCommand("update countPeople set num=" + Application["totol"].ToString(),con); cmd.ExecuteNonQuery(); con.Close(); }
|
Application.Lock();
锁定Application对象, 别的进程必须等UNLOCK后才能更新Application内容.防止两个进程同时修改APPLICATION内容.