天天看點

ASP.NET的Application簡介1

ASP.NET中的Application

1、 Application是用于儲存所有使用者共有的資訊。在ASP時代,如果要儲存的資料在應用程式生存期内不會或者很少改變,那麼使用Application是理想的選擇。但是在ASP。NET開發環境中,程式員通常把類似的配置資料放在Web.config中。如果要使用Application,要注意所有的寫操作度都要在Global.asax檔案中的Application_OnStart事件中完成。

//下面的代碼是在Global.asax檔案中設定
  Application.Lock();
  Application[“UserId”]=”Hello kitty”;
  Application.UnLock();
 // 以下是在頁面中調用Application
  String UserId=Application[“UserId”].ToString();      

 2、Application的特性:

 1、資訊量大小為任意大小

 2、應用于整個應用程式/所有使用者

 3、儲存在伺服器端

 4、作用域和儲存時間是在整個應用程式的生命期

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.IO;
using System.Web.SessionState;
/// <summary>
///Global 的摘要說明
/// </summary>
public class Global : System.Web.HttpApplication
{
    private System.ComponentModel.IContainer component = null;//必要的設計器變量
    private FileStream fileStream;
    private StreamReader reader; //讀字元流
    private StreamWriter writer;//寫字元流

    /// <summary>
    /// 網站程式啟動
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Application_Start(object sender, EventArgs e)
    {
        Application["currentUser"] = 0;//初始化線上使用者
        //加載檔案流,如果檔案不存在則建立檔案
        fileStream = new FileStream(Server.MapPath("~/count.txt"), FileMode.OpenOrCreate);
        reader = new StreamReader(fileStream);//使用流讀取檔案
        Application["AllUser"] = Convert.ToInt32(reader.ReadLine());//将檔案中的記錄存入總通路數中
        reader.Close();//關閉流
    }

    /// <summary>
    /// 會話開始 ,當使用者通路網站時,線上使用者+1,總通路數+1
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Session_Start(object sender, EventArgs e)
    {
        Application.Lock();//鎖定,防止同時錄入
        Application["currentUser"] = (int)Application["currentUser"] + 1;
        Application["AllUser"] = (int)Application["AllUser"] + 1;
        fileStream = new FileStream(Server.MapPath("~/count.txt"), FileMode.OpenOrCreate, FileAccess.Write);
        //寫入流
        writer = new StreamWriter(fileStream);
        //把總通路數再次寫入count.txt檔案中
        writer.WriteLine(Application["AllUser"].ToString());
        writer.Close();//關閉寫入流
        Application.UnLock();//解開鎖定
    }
    /// <summary>
    /// 會話結束
    /// </summary>
    protected void Session_End(object sender, EventArgs e)
    {
        Application.Lock();
        Application["currentUser"] = (int)Application["currentUser"] - 1;
        Application.UnLock();
    }
}      

繼續閱讀