网站的在线人数的统计

 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);
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值