protected void Page_Load(object sender, EventArgs e)
{
//利用全局变量Application进行简单的访问 有可能出现同时访问的问题 需要添加一个互斥锁
/* Response.Write("<h2 align=\"center\">网站计数器的演示</h2>");
if (Application["Counter"] == null)
Application["Counter"] = 1;
else
Application["Counter"] = int.Parse(Application["Counter"].ToString()) + 1;
Response.Write("<p align=\"center\">您是本站第"+Application["Counter"].ToString()+"位访客,欢迎光临</p>");
*/
Application.Lock();
Response.Write("<h2 align=\"center\">网站计数器的演示</h2>");
if (Application["Counter"] == null)
Application["Counter"] = 1;
else
Application["Counter"] = int.Parse(Application["Counter"].ToString()) + 1;
Response.Write("<p align=\"center\">您是本站第" + Application["Counter"].ToString() + "位访客,欢迎光临</p>");
Application.UnLock();
}
//利用Global.asax 由于全局在web服务器停止后不能保存数据需要将数据存储在一个文件里面
public class Global : System.Web.HttpApplication
{
int counter = 0;
protected void Application_Start(object sender, EventArgs e)
{
// int counter = 0;
counter++;
try
{
string rootPath = AppDomain.CurrentDomain.BaseDirectory;
string fileName = rootPath + "counter.txt";
string strCounter = System.IO.File.ReadAllText(fileName, System.Text.Encoding.ASCII);
counter = int.Parse(strCounter);
}
catch (Exception ex)
{
counter = 0;
}
Application.Lock();
Application["counter"] = counter.ToString();
Application.UnLock();
}
protected void Application_End(object sender, EventArgs e)
{
string rootPath = AppDomain.CurrentDomain.BaseDirectory;
string fileName = rootPath + "counter.txt";
string counter = Application["counter"].ToString();
System.IO.File.WriteAllText(fileName, counter, System.Text.Encoding.ASCII);
}