store List in Global.asax

2019-05-28 12:39发布

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条回答
孤傲高冷的网名
2楼-- · 2019-05-28 13:05

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;
查看更多
登录 后发表回答