store List in Global.asax

2019-05-28 12:29发布

问题:

We can store application level strings in a global.asax file like: Global asax:

void Application_Start(object sender, EventArgs e) 
    {
        Application.Lock();
        Application["msg"] = "";            
        Application.UnLock();        
    }

And then in pages we get the "msg" variable as: a.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
 {
        string msg = (string)Application["msg"];
        //manipulating msg..
 }

However, I want to store List of objects as application level variable instead of string msg. I tried this: Global.asax:

void Application_Start(object sender, EventArgs e) 
    {
        Application.Lock();
        List<MyClassName> myobjects= new List<MyClassName>();      
        Application.UnLock();        
    }

a.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
    {
        //here I want to get myobjects from the global.asax and manipulate with it..
    }

So, how to store List myobjects as an application level variable in global.asax and work with this?

Moreover, I have another question: How to send any notification to clients(browsers) when global variable in global.asax is changed?

回答1:

One way would be to store it into the cache :

using System.Web.Caching;    

protected void Application_Start()
{
   ...
   List<MyClassName> myobjects = new List<MyClassName>();
   HttpContext.Current.Cache["List"] = myobjects;
}

then to access / manipulating it :

using System.Web.Caching;

var myobjects =  (List<MyClassName>)HttpContext.Cache["List"];
//Changes to myobjects
...
HttpContext.Cache["List"] = myobjects;